Java 如何以编程方式(在android中动态创建单选按钮)设置选中单选按钮

Java 如何以编程方式(在android中动态创建单选按钮)设置选中单选按钮,java,android,android-studio,retrofit,Java,Android,Android Studio,Retrofit,我试试看 radioButton.setChecked(true) 但它只在第四个单选按钮上起作用。我尝试动态创建单选按钮。我在for循环中创建单选按钮,然后存储单选按钮值。然后还原单选按钮值(也就是说,我有4个选项,我选择了第二个选项并保存了它,然后还原它(setChecked第二个选项)),但它只有setChecked第四个选项 创建单选按钮 for (int k = 0; k < choiceElementList.size(); k++) { if (choiceElement

我试试看

radioButton.setChecked(true)

但它只在第四个单选按钮上起作用。我尝试动态创建单选按钮。我在for循环中创建单选按钮,然后存储单选按钮值。然后还原单选按钮值(也就是说,我有4个选项,我选择了第二个选项并保存了它,然后还原它(setChecked第二个选项)),但它只有setChecked第四个选项

创建单选按钮

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

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

首先为您的
单选按钮设置ID

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

快乐编码…

这是因为您正在将所有RadioButton添加到一个RadioGroup中。当RadioButton在RadioGroup中被选中时,其他RadioButton将被取消选中。你可以清楚地看到这句话:

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

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

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


是的,没错。我将id添加到ArrayList中。我得到了正确的引用(id)。但它只是最后一个标志。
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);
    } 
}
if(choiceElementList.get(k).getId() == Cons.Id){
    radioGroup.check(k);   // K will be your ID Set for your desire RadioButton
}