Android - RadioGroup中多个radiobutton同时被选中问题

问题描述:

动态创建radio button, 并将多个button添加到radio group中。但是实际运行时多个radiobutton会被同时选中:

代码如下:

复制代码
    mRadioGroup = findViewById(R.id.radioGroup);
    mDevButtons = new RadioButton[device_count];
 
    for(int i=0;i<device_count;i++) {
           mDevButtons[i] = new RadioButton(mContext);
           mDevButtons[i].setText(devices[i].getDeviceInfo());

           if(mCurrnetDeviceName != null && devices[i].getDeviceInfo().contains(mCurrnetDeviceName)) {
               mDevButtons[i].setChecked(true);
           }

           final UsbHidDevice device = devices[i];
           mDevButtons[i].setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   mCurrnetDeviceName = device.getDeviceName();
                   if (mCurrnetDeviceName != null) {
                       Toast.makeText(mContext, "Selected device: " + mCurrnetDeviceName, Toast.LENGTH_SHORT).show();
                   }
               }
           });
           mRadioGroup.addView(mDevButtons[i]);
    }

解决方法:

动态创建的radiobutton默认是没有button id的,需要主动分配button id。

mDevButtons[i].setId(View.generateViewId());

复制代码
    mRadioGroup = findViewById(R.id.radioGroup);
    mDevButtons = new RadioButton[device_count];
 
    for(int i=0;i<device_count;i++) {
           mDevButtons[i] = new RadioButton(mContext);
           mDevButtons[i].setText(devices[i].getDeviceInfo());
           mDevButtons[i].setId(View.generateViewId());

           if(mCurrnetDeviceName != null && devices[i].getDeviceInfo().contains(mCurrnetDeviceName)) {
               mDevButtons[i].setChecked(true);
           }

           final UsbHidDevice device = devices[i];
           mDevButtons[i].setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   mCurrnetDeviceName = device.getDeviceName();
                   if (mCurrnetDeviceName != null) {
                       Toast.makeText(mContext, "Selected device: " + mCurrnetDeviceName, Toast.LENGTH_SHORT).show();
                   }
               }
           });
           mRadioGroup.addView(mDevButtons[i]);
    }

解决原因:

radiogoup多个button之间互斥就是通过记录button id实现的。如果radio button没有button id,radio group无法得知具体是哪个button被选中,也就无法实现多个button互斥的功能。

相关推荐
better_liang1 分钟前
每日Java面试场景题知识点之-Docker容器化部署
java·docker·微服务·devops·容器化·企业级开发
悟空码字3 分钟前
SpringBoot整合Kafka,实现高可用消息队列集群
java·spring boot·后端
天天摸鱼的java工程师3 分钟前
从等电梯到写调度系统:一个Java程序员的脑洞实践
java·后端
锅拌饭11 分钟前
IM 推拉的道与术(四)
android
qq_124987075316 分钟前
基于springboot的仁和机构的体检预约系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·mysql·spring·毕业设计·计算机毕业设计
开开心心_Every17 分钟前
免费进销存管理软件:云端本地双部署
java·游戏·微信·eclipse·pdf·excel·语音识别
一个很帅的帅哥21 分钟前
nums.sort()和nums.sort((a, b) => a - b)
javascript
火柴就是我24 分钟前
学习一些常用的混合模式之BlendMode. SRC_OVER
android·flutter
虫小宝25 分钟前
优惠券app安全策略:基于OAuth2.0的第三方平台授权与数据保护
java
资生算法程序员_畅想家_剑魔29 分钟前
Java常见技术分享-29-Jackson JSON处理类详解
java·开发语言·json