我需要动态添加单选按钮,意味着单选按钮可能是3,4,5或6,它将被水平添加,一行包含最多3个单选按钮,如果有超过3则那么它将低于在网格视图中的单选按钮行,我在这里stukking从2天但没有得到任何解决方案..请帮助,任何帮助将非常感谢.. 我的单选按钮代码在下面,但它显示单行中的所有单选按钮,...意味着它隐藏了单选按钮..
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>
和java类是:
@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 :(得分:3)
请尝试以下方式:
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>