动态创建单选按钮

27

我想在 Android 应用程序中创建一系列单选按钮,这些按钮对应于一个字符串数组。这些单选按钮应该切换来自该数组的内容以便在应用程序中显示。请问如何实现?


你有做些什么吗?展示你的进度,这样我们就可以帮助你了。 - Mojo Risin
1个回答

66

你必须将单选按钮添加到RadioGroup中,然后再将RadioGroup添加到layout中。

我缺少一些信息,比如“submit”是什么,但是你的代码应该是这样的:

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();
        }
    });   
}

另一个动态创建单选按钮的代码

<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 I find
     //by id.
     rg.addView(rb, 0, lp);

}

在“ll.removeView(submit);”中,“ll”是什么意思? - partho
1
@partho 我猜它代表了一个LinearLayout实例? - stkent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接