RadioGroup calls onCheckChanged() three times

烈酒焚心 提交于 2019-11-28 05:55:01

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

Call b.setChecked(true); instead.


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

  1. When the current selection is unchecked,
  2. When the new RadioButton is checked, and
  3. When the RadioGroup saves which RadioButton is now checked.

Odd quirk.

Simply post your r.setOnCheckedChangeListener(onPromobuttonsClick); line in onResume() method. It is works for me.

So this is an old one but I also got a similar behavior. A workaround that I found was to call the toggle() method of RadioButton instead of the check() method of RadioGroup.

So in this example, you woulod just need to swap

r.check(R.id.radio1);

with

b.toggle();

since b is already the view with id R.id.radio1.

I had this problem when I wanted to log analytics for radio button presses, but the way the radio groups calls were being handled with .check() caused onCheckedChangeListener to get called multiple times (which sent too many events).

I handled it the following way to only get one event per click:

// create listeners so we don't duplicate the creation in for loop
View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // whatever you want to do here
    }
};

// add on click listener to all radio buttons
int buttonCount = buttonGroup.getChildCount();
for (int i = 0; i < buttonCount; i++) {
    if (buttonGroup.getChildAt(i) instanceof RadioButton) {
        buttonGroup.getChildAt(i).setOnClickListener(onClickListener);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!