我在 RadioGroup 中设置了这些 RadioButtons:
<RadioGroup
android:id="@+id/radioGroupLeakTight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:text="@string/action_yes"
android:id="@+id/radioLeakTightYes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:text="@string/action_no"
android:id="@+id/radioLeakTightNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
使用下面的代码,我尝试通过代码切换其中一个 RadioButtons:
radioGroupLeakTight.check((currentTask.isLeakTight() ? R.id.radioLeakTightYes : R.id.radioLeakTightNo));
如果我不使用上面的代码,RadioButtons 将按预期工作:每当一个被选中时,另一个就会被取消选中。如果我使用代码预先检查其中一个 RadioButton,此功能就会丢失。每当我尝试检查一个 RadioButton 时,另一个保持选中状态。
我已经阅读了我应该实现“OnCheckedChangeListener
”并自行切换它们的解决方案。但我想这只是掩盖了其他不起作用的东西,不是吗?我也读过有这些问题的人,但他们缺少 RadioGroup,我显然有。
我做错了什么?唯一的解决方案是真正实现“OnCheckedChangeListener
”并自己切换其他 RadioButtons 吗?
2016 年 8 月 12 日更新:
所以我继续搜索并实现了“OnCheckedChanged
”。我现在看到的是,每当我检查其中一个 RadioButtons 时,此事件都不会被触发。监听器设置在 2 个 RadioGroups 上。
我开始怀疑这些 RadioButton 失去了他们在 RadioGroup 的成员资格?每当我通过代码检查它们时(在我设置监听器之后),事件就会成功触发。
最佳答案
对 RadioGroup 使用 clearCheck()
。 Learn more .
如果您需要检查另一个 RadioButton,您可以在这之后这样做。
Whenever I try to check a RadioButton, the other one remains checked.
RadioButton radioLeakTightYes = (RadioButton) findViewById(...);
RadioButton radioLeakTightNo = (RadioButton) findViewById(...);
radioGroupLeakTight.clearCheck();
if(currentTask.isLeakTight()){
radioGroupLeakTight.check(radioLeakTightYes.getId());
} else {
radioGroupLeakTight.check(radioLeakTightNo.getId());
}
关于android - 以编程方式选中的 RadioButton 不会取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41019218/