您的位置:首页 > 大数据 > 人工智能

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

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息