Dialog中存在radiogroup动态添加radiobutton的ID问题
2017-09-04 16:58
501 查看
Radiogroup动态弹窗取消再次弹出选中Radiobutton时,报错
今天在做一个Dialog中动态添加Radiogroup的子项Radiobutton功能时,出现一个错误。直接上代码:String checkedName;String[] names=new String[]{"张三","李四","王五"}; private void getRadiogroupDailog(){ View view=LayoutInflater.from(mActivity).inflate(R.layout.students_radiogroup,null); RadioGroup radioGroup= (RadioGroup) view.findViewById(R.id.rg_students); for(int i=0;i<names.length;i++){ RadioButton radioButton=new RadioButton(mActivity); radioButton.setText(names[i]); radioButton.setTextSize(20); radioButton.setPadding(40,10,0,10); radioGroup.addView(radioButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); } radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { checkedName=names[checkedId]; } }); new AlertDialog.Builder(mActivity).setTitle("选择学员") .setView(view) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtils.showMessage(mActivity,checkedName); } }).show(); }
xml布局很简单,就是一个Radiogroup:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><RadioGroupandroid:id="@+id/rg_students"android:layout_width="match_parent"android:layout_height="match_parent"></RadioGroup></LinearLayout>OK,运行项目,测试时发现,点击一次弹出Dailog,不选中任何选项,点击空白处让Dailog消失,再次点击弹出Dailog,随便选中一个子项。报如下错误:
数组下标越界,原因是动态设置Radiobutton时未设置Radiobutton的ID,导致选中时checkid超过了数组本身的长度。
解决方法,为每个Radiobutton设置ID,代码如下:
添加设置ID这句代码后,再次测试,功能正常。
相关文章推荐
- android 动态添加组件(RadioGroup 添加RadioButton和其他组件的一些问题)
- RadioGroup动态添加RadioButton,并且获得事件
- RadioGroup中动态添加RadioButton,RadioButton状态紊乱
- Android 代码中动态为RadioGroup添加RadioButton
- RadioGroup动态添加RadioButton,RadioButton设置默认选中第一个,点击其他的RadioButton第一个不再选中,第一个不再选中
- android中radioGroup动态添加radioButton
- Android 动态生成 radiobutton 解决 radiogroup 多行显示的问题 单选
- 硬编码写RadioGroup的时候要注意RadioButton的id重复问题
- RadioGroup动态添加RadioButton,并且获得事件
- Android中RadioGroup在代码中动态添加子控件RadioButton
- 自定义RadioGroup动态添加RadioButton,并获取选中radioButton的位置
- 动态添加RadioGroup组件的RadioButton出现多选状况解决
- Android布局中有两个RadioGroup的RadioButton选中问题
- 雾山的Anrdoid学习笔记---CheckBox,RadioGroup&RadioButton
- RadioButton动态添加以及需要注意的问题
- Android的ListView中给RadioGroup添加setOnCheckChangeListener的问题之一
- RadioGroup调用check(id)方法时,OnCheckedChangedListener被多次回调问题
- 解决RadioButton与RadioGroup在某些机型偏移问题
- 关于LinnerLayout动态添加的控件 并且给子控件动态设置Id 、点击的问题
- 解决某些手机RadioGroup中的RadioButton不居中问题