动态单选按钮控件
问题描述:
代码... {动态单选按钮控件
private void createRadioButton() {
final RadioButton[] rb = new RadioButton[5];
for(int i=0; i<5; i++){
rb[i] = new RadioButton(this);
ll.addView(rb[i]);
rb[i].setText("Test");
}
ll.addView(submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
ll.removeView(rb[i]);
}
ll.removeView(submit);
Questions();
}});
}
我遇到的问题是,单选按钮出现,用户可以选择任何一个。作为一个初学者,我确定我没有正确设置单选按钮。用户可以选择全部五个按钮,然后一旦选择他们也不能取消选中它们。用户应该只能从五个选项中选择一个选项......我如何使这个可能?
答
您必须添加单选按钮到RadioGroup,然后RadioGroup中布局
我错过喜欢的是提交的,但你的代码看起来应该像一些信息:
private void createRadioButton() {
final RadioButton[] rb = new RadioButton[5];
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
for(int i=0; i<5; i++){
rb[i] = new RadioButton(this);
rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
rb[i].setText("Test");
}
ll.addView(rg);//you add the whole RadioGroup to the layout
ll.addView(submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
rg.removeView(rb[i]);//now the RadioButtons are in the RadioGroup
}
ll.removeView(submit);
Questions();
}
});
}
答
你必须在布局文件中创建一个RadioGroup中
<TableRow>
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/radiobuttons">
</RadioGroup>
</TableRow>
,然后以编程按钮添加到它:
public void makeRadioButtons(Vector tmpVector, int i,
LinearLayout.LayoutParams lp)
{
RadioButton rb = new RadioButton(this);
rb.setText((String) tmpVector.elementAt(i));
//rg is private member of class which refers to the radio group which you can find by id.
rg.addView(rb, 0, lp);
}
希望这会有所帮助。
答
您的布局。
<LinearLayout
android:id="@+id/linearMain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
</RadioGroup>
</LinearLayout>
代码
RadioGroup rg = (RadioGroup) findViewById(R.id.radiogroup);//not this RadioGroup rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
for(int i=0; i<5; i++)
{
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText("Test");
}
希望这有助于你。
:如何添加ID? – 2012-04-04 06:06:12
@ShahzadImam setId()怎么样? – spaaarky21 2013-05-30 18:29:30