我有以下代码:
@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);
即使上面的代码工作正常我的问题是有更好的方法吗?因为这似乎是我重复代码,并且作为新开发人员不能找出任何其他方式来做到这一点。
答案 0 :(得分: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");