一种情况,三种不同的方法。
一(变量在活动顶部声明为私有):
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
}
}
});
哪一个是“最好”的方法,或者它不介意?