本文主要是介绍RadioGroup中RadioButton默认选中问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当一个RadioGroup(其实只要在同一个父布局)中有若干个RadioButton时,RadioButton之间存在着互斥关系,
也就是说只能选中一个RadioButton。但是如果我们需要默认选中某个RadioButton该如何处理呢?
很简单,我们一般情况下会觉得很简单,假如我们需要设置第一个位置的radiobutton默认选中,直接会写到
for (int i = 0; i < 3; i++) { RadioButton radioButton = new RadioButton(this);if(i == 0){radioButton.setChecked(true); } }
然后我们运行发现,没有问题,默认选中了。就这么简单..但是你点一下其他的就会发现,wtf...点击其他的,这个默认选中的不会被取消掉啊....
解决办法:
就是new radiobutton 的时候 给radiobutton设置一个id,如下:
for (int i = 0; i < 8; i++) {RadioButton radioButton = new RadioButton(this);radioButton.setText(i + "");radioButton.setId(i);radioGroup.addView(radioButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
//默认选中第一个按钮
radioGroup.check(0);
然后运行,发现完美解决。
倘若业务需要修改,查看 ,删除的各种业务逻辑的情况的时候 参考我下面的代码设置
for (int j = 0; j < dicBeans.size(); j++) {RadioButton radioButton = new RadioButton(context);LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);radioButton.setText(dicBeans.get(j).getDicName());radioButton.setTag(formDetail.getTableDetailID());radioButton.setId(j);rgTypeEight.addView(radioButton, params);if (mIntentFrom == FLAG_SHOW ) {//查看radioButton.setEnabled(false);if(dicBeans.get(j).getDicName().equals(formDetail.getuValue())){rgTypeEight.check(j);}} else if(mIntentFrom == FLAG_UPDATE ){//修改radioButton.setEnabled(true);if(dicBeans.get(j).getDicName().equals(formDetail.getuValue())){rgTypeEight.check(j);}} else {//添加rgTypeEight.check(0);radioButton.setEnabled(true);}}
如果还有其他问题,请加我的qq群:开发一群:454430053 开发二群:537532956
开发一群:454430053 开发二群:537532956
这篇关于RadioGroup中RadioButton默认选中问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!