如何以编程方式设置Checked单选按钮(动态创建的单选按钮)

时间:2018-10-20 10:19:32

标签: java android android-studio retrofit

我尝试

radioButton.setChecked(true);

,但它唯一的第4个单选按钮。我尝试动态创建单选按钮。我在for循环中创建单选按钮,然后存储单选按钮值。然后还原单选按钮的值(这意味着,我当时有4个选项,我选择了2nd选项并保存并随后将其还原(setChecked 2nd选项)),但只有其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);
}

3 个答案:

答案 0 :(得分: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
}

快乐编码...

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

  

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

     

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

     

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

相关问题