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

相关推荐
今天不要写bug3 分钟前
基于elementUI实现一个可编辑的表格(简洁版)
前端·javascript·elementui
一只小阿乐6 分钟前
vue-router 的实现原理
前端·javascript·vue.js·路由·vue-router
Zz_waiting.7 分钟前
案例开发 - 日程管理 - 第七期
开发语言·前端·javascript·vue.js·html·路由
叫我阿柒啊7 分钟前
Java全栈开发面试实战:从基础到微服务的完整技术栈解析
java·spring boot·微服务·前端框架·vue·jwt·全栈开发
writeone8 分钟前
9-10关于JS初学产生的问题
开发语言·javascript·ecmascript
前行的小黑炭8 分钟前
Android:在项目当中可能会遇到的ANR,应该如何解决?
android·java·kotlin
一只小风华~10 分钟前
Vue:事件处理机制详解
前端·javascript·vue.js·typescript·前端框架
索迪迈科技1 小时前
Flink Task线程处理模型:Mailbox
java·大数据·开发语言·数据结构·算法·flink
老衲不服4 小时前
android 三方sdk minSdkVersion 兼容问题处理
android