0

我有以下代码:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);    

        final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
        int defaultValue = rg_numberOfQuestions.getId();
        RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(getPref(defaultValue, "NQ")));
        if(rbtn!=null)
            rbtn.setChecked(true);
        rg_numberOfQuestions.setOnCheckedChangeListener(this);

        final RadioGroup rg_numbersBetween = (RadioGroup) findViewById(R.id.radioGroupNumbersBetween);   
        int defaultValue1 = rg_numbersBetween.getId();
        RadioButton rbtn1 = ((RadioButton) rg_numbersBetween.findViewById(getPref(defaultValue1, "NB")));
        if(rbtn1!=null)
            rbtn1.setChecked(true);
        rg_numbersBetween.setOnCheckedChangeListener(this);     
    }   

如您所见,相同的代码重复了两次,这就是这部分:

int defaultValue = rg_numberOfQuestions.getId();
        RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(getPref(defaultValue, "NQ")));
        if(rbtn!=null)
            rbtn.setChecked(true);
        rg_numberOfQuestions.setOnCheckedChangeListener(this);

即使上面的代码工作正常,我的问题是有更好的方法吗?因为这似乎我正在重复代码,并且作为新开发人员无法找出任何其他方式来做到这一点。

4

1 回答 1

0

你可以实现这个方法:

selectSavedRadioButton(RadioGroup group, String savedButtonPreferencesKey) {
    RadioButton button = (RadioButton) group.findViewById(getPref(group.getId(), preferencesKey));
    if (button != null) {
        button.setChecked(true);
    }
}

你可以这样称呼它:

RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
selectSavedRadioButton(rg_numberOfQuestions, "NQ");
于 2013-10-02T23:24:48.243 回答