Reputation: 16825
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?
Upvotes: 0
Views: 112
Reputation: 43
I think using 'one' would be the best way way, because private is usually treated like final when compiled. Secondly the access settings for final and private are the same.
Upvotes: 1
Reputation: 137398
I don't think there is any difference between one and two. Three however, will suffer a performance penalty, because every time onCheckedChanged
is fired, it will have to call findViewById
for each radio button. The other methods are "caching" a reference to the RadioButton
.
Upvotes: 4