一种情况,三种不同的方法。
一个(变量在活动顶部声明为私有):
radioGroup = (RadioGroup) findViewById(R.id.RadioGroup);
radioButton1 = (RadioButton) findViewById(R.id.RadioButton1);
radioButton2 = (RadioButton) findViewById(R.id.RadioButton2);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radioButton1.isChecked()) {
// do something
} else if (radioButton2.isChecked()) {
// do something
}
}
});
两个
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.RadioGroup);
final RadioButton radioButton1 = (RadioButton) findViewById(R.id.RadioButton1);
final RadioButton radioButton2 = (RadioButton) findViewById(R.id.RadioButton2);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radioButton1.isChecked()) {
// do something
} else if (radioButton2.isChecked()) {
// do something
}
}
});
三
((RadioGroup) findViewById(R.id.RadioGroup)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (((RadioButton) findViewById(R.id.RadioButton1)).isChecked()) {
// do something
} else if (((RadioButton) findViewById(R.id.RadioButton2)).isChecked()) {
// do something
}
}
});
哪一个是“最佳”方法还是不介意?
答案 0 :(得分:4)
我认为一和二之间没有任何区别。但是,三会遭受性能损失,因为每次onCheckedChanged
被触发时,都必须为每个单选按钮调用findViewById
。其他方法是“缓存”对RadioButton
的引用。
答案 1 :(得分:1)
我认为使用'one'将是最好的方式,因为私有通常在编译时被视为final。其次,final和private的访问设置是相同的。