android - 当选中同一 RadioGroup 中的另一个 RadioButton 时,RadioButton 不会取消选中

标签 android radio-button radio-group

这是重复项:Android dynamically generated radio buttons not unchecking once setChecked programmatically

但是,在该问题中,答案并没有解决问题,因为我添加的所有尝试解决问题的代码都使问题变得困惑。此外,从那时起我还应用了以下几种可能的解决方案。

问题是,如果我以编程方式检查 RadioButton,当我选择同一 RadioGroup 中的另一个 RadioButton 时,它会保持选中状态。

我从谷歌搜索中了解到一些我已经应用但尚未奏效的潜在解决方案,例如:

  • Using RadioGroup.Check instead of RadioButton.setCheck
  • specifying each RadioButton's Id explicitly
  • Adding the RadioButton to the RadioGroup before checking it
  • Adding all the RadioButtons to the RadioGroup before checking one of them

尽管如此,当您单击另一个单选按钮时,单选按钮仍然保持选中状态。

   private void PopulateAccessPoints(List<clsAccessPoint> accessPoints){
        try{
            rg = new RadioGroup(this);
            rlaAccessPoints.addView(rg);
            int i = 0;
            for (clsAccessPoint acp :  accessPoints) {
                i++;
                RadioButton rd = new RadioButton(this);
                rg.addView(rd);
                rd.setId(i);
                rd.setText(acp.ID + ": " + acp.Name);
            }

            rg.check(rg.getChildAt(1).getId());

            } catch (Exception ex) {
                ex.printStackTrace();
        }

注意:应该检查的RadioButton将动态确定,但我已经对其进行了硬编码,因为上面表现出相同的症状并且更简单。

我现在已经花了几个小时来解决这个问题,因此非常感谢您对这个显然非常简单的问题的任何帮助!

最佳答案

            RadioButton rd = new RadioButton(this);
            rg.addView(rd);
            rd.setId(i);
            rd.setText(acp.ID + ": " + acp.Name);

尝试将此代码移动为如下所示:

            RadioButton rd = new RadioButton(this);
            rd.setId(i);
            rd.setText(acp.ID + ": " + acp.Name);
            rg.addView(rd);

在将其添加到组之前设置 ID 吗?

关于android - 当选中同一 RadioGroup 中的另一个 RadioButton 时,RadioButton 不会取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436756/

相关文章:

android - 撤消Android应用程序上的谷歌帐户访问确认

javascript - 单选按钮不会选中/取消选中

android - 我如何安排 RadioButtons?

javascript - 单选按钮验证

android - 我怎样才能让我的按钮在 radiogroup 上居中?

android - 如何更改布局上 RadioGroup 的大小?

java - Android 在内部与外部导入库的好处

android - DaggerMock 库 - 它如何覆盖模块?

android - 为什么在使用onclicklistener时我的应用程序崩溃了?

php - 使用 css 单击时更改单选按钮的图像