如何在不知道确切计数的情况下创建单选按钮

时间:2011-08-09 09:30:34

标签: android list radio-button

如何在文件布局中的radioGroup中创建单选按钮,而不知道确切的计数

任何人都有任何想法吗?

2 个答案:

答案 0 :(得分:3)

我要求你清楚地说出来,但是当我得到的时候,你想要多个单选按钮,

Take a loop and create dynamic RadioButton add these button to Radio Group  

答案 1 :(得分:2)

可能这有任何帮助;

public class RadDemoActivity extends Activity {

    private RadioGroup radGroup;
    private Button addButton;
    private RadioButton radButton;

    private static int no;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        no=0;

        doInflateItems();

        setAddButton();
    }


    private void doInflateItems() {

        radGroup = (RadioGroup) findViewById(R.id.radGroup);
        addButton = (Button) findViewById(R.id.addRad);
    }


    private void setAddButton() {

        addButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                radButton = new RadioButton(getApplicationContext());
                radButton.setText("Option " + no++);

                radGroup.addView(radButton);
            }
        });
    }
}

XML布局:

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

    <Button android:id="@+id/addRad" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Add" />


    <ScrollView android:id="@+id/vScroll" android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <RadioGroup android:id="@+id/radGroup"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />

    </ScrollView>
</LinearLayout>

此代码通过按钮单击添加单选按钮,如果要一次添加多个按钮,可以从循环中执行相同操作。希望这会有所帮助。