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