RadioGroup 调用 onCheckChanged() 三次RadioGroup、onCheckChanged

2023-09-06 19:04:11 作者:望着天空回忆他╮

我一直在努力解决 RadioButton 的编程检查问题,该 RadioButton 位于 RadioGroup 中.似乎单个 check() 调用会引发三个事件 - 第一个 RadioButton 一次,第二个 RadioButton 两次,这是我的目标.同时点击界面中的第二个RadioButton,只会出现一个事件,没错.

I've been struggling with an issue of programmatic checking of a RadioButton, which is situated in a RadioGroup. It seems that a single check() call raises three events - once for the first RadioButton and twice for the second, which is my target. At the same time clicking on the second RadioButton in the interface causes only one event to appear, which is correct.

那么,有没有办法避免多个事件引发?

So, is there a way to avoid multiple event raising ?

public class RadiogroupActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        RadioGroup r = (RadioGroup) findViewById(R.id.radioGroup1);
        RadioButton b = (RadioButton) findViewById(R.id.radio1);
        r.setOnCheckedChangeListener(onPromobuttonsClick);
        r.check(R.id.radio1);

    }

    private OnCheckedChangeListener onPromobuttonsClick = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            Log.d("x", "x");
        }
    };
}

推荐答案

那么,有没有办法避免多个事件引发?

So, is there a way to avoid multiple event raising ?

调用 b.setChecked(true); 代替.

快速浏览 源代码确认 RadioGroup#check() 确实确实调用了 OnCheckChangedListener 三次...

A quick look through the source code confirms that RadioGroup#check() really does call the OnCheckChangedListener three times...

当当前选择未被选中时,当新的 RadioButton 被选中时,并且当 RadioGroup 保存现在检查哪个 RadioButton 时.

奇怪的怪癖.