【问题标题】:how to setChecked radio button in programmatically (radio button created in dynamically ) android如何以编程方式设置Checked单选按钮(动态创建的单选按钮)android
【发布时间】:2019-03-25 01:37:22
【问题描述】:

我试试看

radioButton.setChecked(true);

但它唯一有效的第四个单选按钮。我尝试动态创建单选按钮。我在 for 循环中创建单选按钮,然后存储单选按钮值。然后恢复单选按钮的值(也就是说,当我选择第二个选项并保存它然后恢复它时,我有 4 个选项(setChecked 2nd option))但它只有 setChecked 4th 选项。

创建单选按钮。

for (int k = 0; k < choiceElementList.size(); k++) {
  if (choiceElementList.get(k).dataFormatId == 1) {
    radioButton = new RadioButton(getContext());
    radioButton.setText(choiceElementList.get(k).getDataFormatValue());
    radioButton.setLayoutParams(params1);
    radioButton.setPadding(0, 5, 0, 5);
    Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
    radioGroup.addView(radioButton);
  } 
}

尝试恢复

if(choiceElementList.get(k).getId() == Cons.Id){
  radioButton.setChecked(true);
}

【问题讨论】:

  • 是的,正确的。我将 id 添加到 ArrayList.

标签: java android android-studio retrofit


【解决方案1】:

首先将 ID 设置为您的 RadioButtons

for (int k = 0; k < choiceElementList.size(); k++) {

    if (choiceElementList.get(k).dataFormatId == 1) {
        RadioButton radioButton = new RadioButton(getContext());

        // Set ID to Radio Button
        radioButton.setId(k);

        radioButton.setText(choiceElementList.get(k).getDataFormatValue());
        radioButton.setLayoutParams(params1);
        radioButton.setPadding(0, 5, 0, 5);
        Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
        radioGroup.addView(radioButton);
    } 
}

现在只需使用您的 RadioGroup 来检查欲望 RadioButton 及其 ID

if(choiceElementList.get(k).getId() == Cons.Id){
    radioGroup.check(k);   // K will be your ID Set for your desire RadioButton
}

快乐编码...

【讨论】:

    【解决方案2】:

    根据此代码段,您的 radioButton 变量仅引用最后创建的元素(单选按钮)。这就是为什么它只标记第四个。您需要为您想要的单选按钮获取正确的参考。

    【讨论】:

    • 我得到了正确的参考 (id)。但它唯一的标记是最后一个。
    【解决方案3】:

    这是因为您将所有 RadioButton 添加到 RadioGroup 中。在 RadioGroup 中选中 RadioButton 时,将取消选中其他 RadioButton。你可以看RadioGroup documentation说清楚:

    此类用于为一组单选按钮创建多重排除范围。选中一个属于单选组的单选按钮会取消选中同一组中任何先前选中的单选按钮。

    最初,所有单选按钮都未选中。虽然无法取消选中特定单选按钮,但可以清除单选组以移除选中状态。

    选择由 XML 布局文件中定义的单选按钮的唯一 ID 标识。

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 2018-07-15
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 2013-07-09
      相关资源
      最近更新 更多