我可以在其中创建带有RadioButtons的动态RadioGroup(w / o xml)吗?

时间:2012-03-25 15:55:56

标签: android android-layout

我想在onCreate函数中创建其中包含RadioButton列表的RadioGroup。我希望使用xml-layout进行锻炼。可能吗?谢谢。

2 个答案:

答案 0 :(得分:4)

这样的事情:

....
RadioGroup group = new RadioGroup(this); 
group.setOrientation(RadioGroup.HORIZONTAL);
RadioButton btn1 = new RadioButton(this);
btn1.setText("BTN1");
group.addView(btn1);
RadioButton btn2 = new RadioButton(this);
group.addView(btn2);
btn2.setText("BTN2");
.... 
RadioButton btnN = new RadioButton(this);
group.addView(btnN);
btnN.setText("BTNN");
yourLayout.addView(group);
....

答案 1 :(得分:2)

这将完成这项工作:

    int buttons = 5;

    RadioGroup rgp = new RadioGroup(getApplicationContext());

    for (int i = 1; i <= buttons; i++) {
        RadioButton rbn = new RadioButton(this);
        rbn.setId(1 + 1000);
        rbn.setText("RadioButton" + i);
        //Attach button to RadioGroup.
        rgp.addView(rbn);
    }

    ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);
    viewGroup.addView(rgp);

这是一个完整的例子:

public class MainActivity extends AppCompatActivity {

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Defining buttons quantity!
        int buttons = 5;

        //Create a new instance of RadioGroup.
        RadioGroup rgp = new RadioGroup(getApplicationContext());

        //Create buttons!
        for (int i = 1; i <= buttons; i++) {
            RadioButton rbn = new RadioButton(this);
            rbn.setId(1 + 1000);
            rbn.setText("RadioButton" + i);
            //Attach button to RadioGroup.
            rgp.addView(rbn);
        }

        //Get the root view.
        ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
                .findViewById(android.R.id.content)).getChildAt(0);
        viewGroup.addView(rgp);


    }
}

这就是结果:

enter image description here

如果您需要使用在xml布局中定义的RadioGroup并添加dinamically按钮,请参阅this answer