【发布时间】:2023-03-11 00:54:01
【问题描述】:
我在 android 中从服务器返回的 json 数据动态生成单选按钮。
我可以在单选组中显示单选按钮。还可以获取每个单选按钮的 id。
但是当我点击下一个单选按钮时,所有按钮都保持选中状态。没有一个是未经检查的。
由于无线电号码是动态生成的,因此它的大小会有所不同。
我的代码 sn-ps:
if(type.equals("radio_buttons")){
String optionName = regData.getOption();
optionName = Character.toString(optionName.charAt(0)).toUpperCase()+optionName.substring(1);
List listItem = new ArrayList();
listItem.add(optionName);
final RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);
final int radioSize = listItem.size();
final RadioButton[] rb = new RadioButton[radioSize];
for(int i=0; i<radioSize; i++){
rb[i] = new RadioButton(getActivity());
rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
rb[i].setId(i);
rb[i].setText(optionName);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for(int j = 0; j<radioSize; j++){
rg.removeViewAt(checkedId);
}
/*
switch (checkedId)
{
case 1:
Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();
case 2:
Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();
}*/
}
});
this.linearLayout.addView(rg);
}
如何在 android 中选择一个单选按钮时清除/取消选中其他单选按钮?
【问题讨论】:
-
尝试为每个单选按钮添加一个 id
-
@zozelfelfo 添加了。你能告诉我现在该怎么做吗?
-
for(int j = 0; j
-
@user3676184 没有。这就是为什么张贴在这里。您知道需要修复的地方吗?
-
我想你会在这之后得到 NPE for loop.for(int j = 0; j
标签: android android-layout android-activity radio-button