One situation, three different approaches.
One (variables are declared at the top of the activity as private):
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
}
}
});
Two:
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
}
}
});
Three:
((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
}
}
});
Which one is the “best” approach or it doesn’t mind?
I don’t think there is any difference between one and two. Three however, will suffer a performance penalty, because every time
onCheckedChangedis fired, it will have to callfindViewByIdfor each radio button. The other methods are “caching” a reference to theRadioButton.