问题描述
单击单选按钮时,我正在尝试执行以下操作:
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)
}
}
在另一个功能中,有一个clearCheck
用来清除单选按钮.问题是每次调用clearCheck
时,也会调用监听器setOnCheckedChangeListener
.
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?
推荐答案
/**
* <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);
}
在RadioGroup上调用clearCheck()
方法时,如果选中了RadioButton,它将将该视图的状态设置为未选中,然后通过调用onCheckedChanged()
通知应用程序有关单选按钮状态更改的信息.您传入setOnCheckedChangeListener()
方法的实例的方法.
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.
这说明了为什么在您的应用中,如果用户选择了错误的答案,它将两次调用onCheckedChange()
.前者是状态从未选中变为已选中时,后者是状态通过clearCheck()
从选中变为未选中.这是预期的行为.
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.
解决方案::在调用clearCheck()
方法之前清除OnCheckedChangeListener,然后在调用clearCheck()
方法之后进行设置.
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)
}
这篇关于Android RdioGroup clearCheck与setOnCheckedChangeListener冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!