【问题标题】:Can I create dynamically RadioGroup with RadioButtons inside it (w/o xml)?我可以在其中动态创建带有单选按钮的 RadioGroup(没有 xml)吗?
【发布时间】:2012-04-09 07:59:39
【问题描述】:

我想在 onCreate 函数中创建 RadioGroup,其中包含 RadioButton 列表。我想使用 xml-layout 将其作为练习来完成。可能吗?谢谢。

【问题讨论】:

标签: android android-layout


【解决方案1】:

类似这样的:

....
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);
....

【讨论】:

    【解决方案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);
    
    
        }
    }
    

    结果如下:

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

    【讨论】:

    • 如何获取动态创建的选中电台的值?
    猜你喜欢
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多