首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以在里面动态创建包含RadioButtons的RadioGroup (没有xml)吗?

我可以在里面动态创建包含RadioButtons的RadioGroup (没有xml)吗?
EN

Stack Overflow用户
提问于 2012-03-25 23:55:56
回答 2查看 9.7K关注 0票数 4

我想在onCreate函数中创建包含RadioButton列表的RadioGroup。我想在没有使用xml-layout的情况下作为练习。有可能吗?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-26 00:01:13

如下所示:

代码语言:javascript
复制
....
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);
....
票数 4
EN

Stack Overflow用户

发布于 2016-11-30 03:58:46

这将完成以下工作:

代码语言:javascript
复制
    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);

这是一个完整的示例:

代码语言:javascript
复制
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);


    }
}

这就是结果:

如果需要使用定义到xml布局中的RadioGroup并动态添加按钮,请参见this answer

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9861563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档