android - 动态单选按钮控件

标签 android

代码...{

private void createRadioButton() {

        final RadioButton[] rb = new RadioButton[5];
        for(int i=0; i<5; i++){
            rb[i]  = new RadioButton(this);
            ll.addView(rb[i]); 
            rb[i].setText("Test");
         }
         ll.addView(submit); 
          submit.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                for(int i = 0; i < 5; i++) { 
                    ll.removeView(rb[i]); 
                }  
                ll.removeView(submit);
                Questions();
         }});   
    }

我遇到的问题是单选按钮出现,用户可以选择任何一个。作为初学者,我确定我没有正确设置单选按钮。用户可以选择所有五个按钮,然后一旦选择,他们也不能取消选中它们。用户应该只能从五个选项中选择一个选项...我怎样才能做到这一点?

最佳答案

您必须将单选按钮添加到 RadioGroup然后将 RadioGroup 添加到布局中

我错过了一些信息,例如提交的内容,但您的代码应该如下所示:

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

关于android - 动态单选按钮控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669104/

相关文章:

java - 在 Retrofit Android 中获取响应

Android:使用 LocationManager.requestLocationUpdates() 时如何从 Intent bundle 中获取位置信息

android - Android Studio IDE 上的文本/设计选项卡缺少新的 Android 项目

Android - 如何知道我失去了检查通话的权限(在 Marshmallow 上)

android - 多个设备中的自签名 SSL 证书 - 这足够安全吗?

android - 在 Chrome 自定义选项卡的标题中插入参数

android - LibGdx Assetmanager 加载无效行

android - 如何检测应用程序的关闭并采取措施? ( Kotlin )

java - 检测手机是否插入电脑

java - Android - 如何强制 child 覆盖具有代码的父方法