1つの状況、3つの異なるアプローチ。
1つ(変数はアクティビティの上部でプライベートとして宣言されます):
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
}
}
});
どちらが「最良の」アプローチですか、それとも気にしませんか?