android - 以编程方式选中的 RadioButton 不会取消选中

标签 android radio-button radio-group

我在 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/

相关文章:

android - 在运行时更改改造 okhttp 客户端

php - 有没有办法让 flutter webview 使用 android 相机上传文件?如何在 webview_flutter flutter 中打开文件选择器?

ruby-on-rails-3 - rails,simple_form,保存后如何用所选选项更新单选按钮?

html - 自定义单选按钮不可见

android - 当我切换 Activity 时,RadioGroup 成员按钮不断更改 ID

java - <Android>无法启动 Activity ComponentInfo

android - 是否有适用于 Android 汽车的基于 ARM 的系统镜像?

jquery 检查具有特定值的单选按钮

wpf - 垂直对齐 WPF RadioButton 项目符号并拉伸(stretch)其内容

java - 使用集合 .txt 文件中的 Map TreeSet 对单选按钮进行分组