添加单选按钮动态︰android

添加单选按钮动态︰android

问题描述:

我需要添加单选按钮动态,意味着单选按钮可能是3,4,5或6,它将被添加水平和一行包含最多3单选按钮,如果有更多然后3那么它会出现在网格视图上方的单选按钮的下方,我在这里工作2天,但没有得到任何解决方案..请帮助,任何帮助将不胜感激.. 我的单选按钮代码如下但它在单排显示所有单选按钮,..意味着其隐藏所述单选按钮..添加单选按钮动态︰android

main.xml中:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

    <TextView 
android:id="@+id/TextView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Choose Your Favorite Actress" > 
    </TextView> 

<RadioGroup 
android:id="@+id/RadioGroup01" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" > 
</RadioGroup> 
<Button 
android:id="@+id/Button01" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="Submit" > 
</Button> 
</LinearLayout> 

和J AVA类:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     DisplayRadioButton(); 
    } 


    public void DisplayRadioButton() { 
     for(int i=0;i<10;i++) { 
      RadioGroup radiogroup = (RadioGroup)findViewById(R.id.RadioGroup01); 
      RadioButton rdbtn = new RadioButton(this); 
      rdbtn.setId(i); 
      rdbtn.setText(text[i]); 
      radiogroup.addView(rdbtn); 
    } 

} 
+0

你为什么不采取单选按钮,网格视图,只是根据你的需要更改适配器。 – Shachillies 2012-07-18 08:03:53

+0

hi deepak ..我从来没有用户单选按钮的网格视图,你可以请建议我一些链接,或者如果你可以分享我的代码..我会高度thakfull你 – SRam 2012-07-18 08:50:29

+0

deepak其实在我的项目我有一个需求像我有一个问题,有一些基于这个单选按钮的答案,选项是动态的,一些问题有4个选项,有些有5或6,所以我需要动态实现它..我想你明白我的观点。 .so现在,如果你可以请帮助我 – SRam 2012-07-18 09:13:05

,请通过以下方式尝试:

1)在你的XML中删除RadioGroup中。动态创建它

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]); 


} 

我希望你能解决。注意数组索引超出界限的异常。

你的XML可能看起来像:

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

感谢您的回复,我需要水平设置单选按钮我为什么设置它horizo​​ntolly ..? – SRam 2012-07-18 12:15:37

+0

看到编辑答案,你必须设置根线性布局方向是垂直的,你必须通过水平方向动态创建子线性布局。 – 2012-07-18 12:33:28

+0

现在你是说在你的xml中添加无线组,并在你的java代码中使用XML创建单选按钮的实例,现在删除无线组? – SRam 2012-07-18 13:17:16