首页 > 解决方案 > 如何以编程方式设置Checked单选按钮(动态创建的单选按钮)android

问题描述

我试试

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);
}

标签: javaandroidandroid-studioretrofit

解决方案


首先将 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);
    } 
}

现在只需使用您的 IDRadioGroup来检查欲望RadioButton

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

快乐的编码...


推荐阅读