且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Android应用中动态添加单选按钮

更新时间:2022-12-17 23:22:49

请尝试以下方式:

1)在您的xml中删除 RadioGroup .通过动态创建

1)in your xml remove the RadioGroup. create it by dynamically

RadioGroup radiogroup[];
RadioButton rdbtn[];
LinearLayout linear[]; 

radiogroup = new RadioGroup[9/3];
rdbtn = new RadioButton[9];
linear = new LinearLayout[9/3];

......
int count = 0; // integer flag

for(int i=0;i<9;i++){

  if the value of i is equal to 3 multiple then increase count by 1
         // sett linear[count]'s orientation is horizontal.

         root_layout.addView(linear[count]);
         radiogroup[count] = new RadioGroup(this);
         linear[count].addView(radiogroup[count]);  // add radio group to linear layout

       add radio button to radio group.

          rdbtn[i] = new RadioButton(this);
          rdbtn[i].addView(radiogroup[count]);


}

我希望你能解决.注意数组索引超出范围的异常.

i hope you get solved. be aware of array index out of bound exception.

您的xml可能类似于:

your xml may look like:

<LinearLayout
           android:id= rootlayout
           ..... // the child linearlayout
                     .. . radio group
                        ... radio button
 </LinearLayout>