Android RdioGroup clearCheck conflict with setOnCheckedChangeListener

本秂侑毒 提交于 2021-01-28 10:30:43

问题


I'm trying to take an action when a radio button clicked:

  dataBinding.radioGroup.setOnCheckedChangeListener { radioGroup: RadioGroup, i: Int ->
       
if( radioGroup.checkedRadioButtonId != -1){
        checkAnswer(i)
       }
    }

inside another function there is a clearCheck to clear radio button . the issue is that every time clearCheck is called, the listener setOnCheckedChangeListener also called.

is there any way to run the listener to get run when a radio button is selected and not when it is cleared?


回答1:


/**
 * <p>Interface definition for a callback to be invoked when the checked
 * radio button changed in this group.</p>
 */
public interface OnCheckedChangeListener {
    /**
     * <p>Called when the checked radio button has changed. When the
     * selection is cleared, checkedId is -1.</p>
     *
     * @param group the group in which the checked radio button has changed
     * @param checkedId the unique identifier of the newly checked radio button
     */
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId);
}

When you call clearCheck() method on the RadioGroup, if there is a RadioButton is checked, it will set the state of this view to unchecked, then notify the app about the state of a radio button changed by calling onCheckedChanged() method of the instance that you pass into setOnCheckedChangeListener() method.

This explains why in your app, if users select a wrong answer, it will call onCheckedChange() twice. The former is when the state change from unchecked to checked, the latter is when the state change from checked to unchecked via clearCheck(). This is the expected behavior.

Solution: Clear the OnCheckedChangeListener before calling clearCheck() method, then set it after calling clearCheck() method.

// Declare this variable
private val onCheckedChangeListener = object : RadioGroup.OnCheckedChangeListener {
    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        if (checkedId != -1) {
            checkAnswer(checkedId)
        }
    }
}

// Calling this line once, inside onCreate() of Activity 
// or onCreateView() of Fragment for example
dataBinding.radioGroup.setOnCheckedChangeListener(onCheckedChangeListener)

private fun checkAnswer(checkedId: Int) {
    // Your logic to check answer here
    // ...

    // If the answer is wrong, just clear check
    dataBinding.radioGroup.setOnCheckedChangeListener(null)
    dataBinding.radioGroup.clearCheck()
    dataBinding.radioGroup.setOnCheckedChangeListener(onCheckedChangeListener)
}


来源:https://stackoverflow.com/questions/64591757/android-rdiogroup-clearcheck-conflict-with-setoncheckedchangelistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!