RadioGroup中RadioButton不能互斥

来源:互联网 发布:linux下创建新项目 编辑:程序博客网 时间:2024/06/08 02:27

1,项目需要动态的添加RadioButton,看了一下RadioGroup和RadioButton的使用,觉得很简单,只需要将RadioButton加入RadioGroup中即可,随着功能的逐步完善,需要显示某个默认的选项是出现了问题,当调用RadioButton.setChecked(true)显示默认选项后发现RadioGroup中的RadioButton不能互斥,选中的RadioButton不能改变状态,同时又可以选中其他的RadioButton。经过研究测试,发现不能用这种方式来设置默认选中的项,在xml中设置checked=true也不行,需要用RadioGroup.check(id),来设置被默认选中的项,其中id为RadioButton的id,如果动态添加的RadioButton,需要设置好id,而在XML中则可以声明id来进行选着。

动态添加的代码如下:

layout_group.removeAllViews(); // 清除视图RadioGroup radioGroup = new RadioGroup(this);radioGroup.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));radioGroup.setOrientation(RadioGroup.VERTICAL);int selectId = 0;for (DaAn daAn : daans) {RadioButton radio = new RadioButton(this);radio.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,RadioGroup.LayoutParams.WRAP_CONTENT));radio.setTextColor(getResources().getColor(R.color.radio_text));radio.setTextSize(15);radio.setText(daAn.getName());radio.setId(Integer.valueOf(daAn.getId()));if (answers.size() != 0&& daAn.getId().equals(answers.get(0).getAnSelect())) {selectId = Integer.valueOf(daAn.getId());}radioGroup.addView(radio);}if (selectId != 0) {radioGroup.check(selectId);   //根据这个来设置默认选中的项}layout_group.addView(radioGroup);


原创粉丝点击