0

一种情况,三种不同的方法。

(变量在活动顶部声明为私有):

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
        }
    }
});

哪一个是“最好”的方法,或者它不介意?

4

2 回答 2

4

我觉得一和二没什么区别。然而,三个将遭受性能损失,因为每次onCheckedChanged被触发时,它都必须调用findViewById每个单选按钮。其他方法是“缓存”对RadioButton.

于 2012-12-14T23:42:08.963 回答
1

我认为使用 'one' 将是最好的方法,因为 private 通常在编译时被视为 final。其次,最终和私有的访问设置是相同的。

于 2012-12-14T23:48:17.897 回答