【问题标题】:RadioButton checked programmatically won't uncheck以编程方式检查的 RadioButton 不会取消选中
【发布时间】:2016-12-07 13:51:35
【问题描述】:

我在 RadioGroup 中设置了这些 RadioButton:

<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 会按预期工作:只要一个被选中,另一个就会被取消选中。如果我使用代码预先检查其中一个 RadioButtons,则此功能会丢失。每当我尝试检查 RadioButton 时,另一个仍处于选中状态。

我已经阅读了应该实现“OnCheckedChangeListener”并自己切换它们的解决方案。但我想这只是掩盖了其他不起作用的东西,不是吗?我也读过有这些问题的人,但他们缺少 RadioGroup,我显然有。

我做错了什么?唯一的解决方案是真正实现“OnCheckedChangeListener”并自己切换其他 RadioButtons 吗?

2016 年 8 月 12 日更新:

所以我继续搜索并实现了“OnCheckedChanged”。我现在看到的是,每当我检查其中一个 RadioButtons 时,这个事件都不会被触发。侦听器设置在 2 个 RadioGroups 上。 我开始怀疑这些 RadioButtons 失去了 RadioGroup 的成员资格?每当我通过代码检查它们时(在我设置我的侦听器之后),事件就会成功触发。

【问题讨论】:

    标签: android radio-button radio-group


    【解决方案1】:

    对 RadioGroup 使用 clearCheck()Learn more。 如果您需要检查另一个 RadioButton,您可以在此之后进行。

    每当我尝试检查一个 RadioButton 时,另一个仍然处于选中状态。

    RadioButton radioLeakTightYes = (RadioButton) findViewById(...);
    RadioButton radioLeakTightNo = (RadioButton) findViewById(...);
    
    radioGroupLeakTight.clearCheck();
    if(currentTask.isLeakTight()){
        radioGroupLeakTight.check(radioLeakTightYes.getId());
    } else {
        radioGroupLeakTight.check(radioLeakTightNo.getId());
    }
    

    【讨论】:

    • 使用 clearCheck 表示我应该实现监听器。这真的是唯一的方法吗?
    • 编辑会让你明白我的意思。这适用吗?
    • 对不起,我的问题可能不够清楚。我知道如何通过代码清除和切换 RadioButtons。但是在我以编程方式检查其中一个之后,当用户尝试使用它时,自动切换功能就会丢失。然后将检查这两个值。
    • 是的,没错。所以,你应该使用监听器。您可以clearCheck() 并在OnCheckedChangeListener 中启用另一个 RadioButton。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2014-02-19
    相关资源
    最近更新 更多