Dialog中存在radiogroup动态添加radiobutton的ID问题

来源:互联网 发布:js 获取html属性值 编辑:程序博客网 时间:2024/06/04 19:28

     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">    <RadioGroup        android: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这句代码后,再次测试,功能正常。

阅读全文
0 0
原创粉丝点击