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互斥的功能。

相关推荐
图王大胜25 分钟前
Android SystemUI组件(11)SystemUIVisibility解读
android·framework·systemui·visibility
程序员南飞1 小时前
ps aux | grep smart_webrtc这条指令代表什么意思
java·linux·ubuntu·webrtc
弥琉撒到我2 小时前
微服务swagger解析部署使用全流程
java·微服务·架构·swagger
一颗花生米。2 小时前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
问道飞鱼2 小时前
Java基础-单例模式的实现
java·开发语言·单例模式
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19952 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
勿语&3 小时前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
服装学院的IT男4 小时前
【Android 13源码分析】Activity生命周期之onCreate,onStart,onResume-2
android
Arms2064 小时前
android 全面屏最底部栏沉浸式
android