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

相关推荐
2501_916766541 分钟前
【Java】代理模式---静态代理与动态代理
java·开发语言·代理模式
纸带2 分钟前
USB CDC 配置描述符中对比两个CDC设备配置
java·网络·windows
AAA阿giao7 分钟前
用 LangChain 玩转大模型:从零搭建你的第一个 AI 应用
javascript·人工智能·langchain·llm·ai编程·ai开发
缺点内向7 分钟前
Java:轻松实现 Excel 文档属性添加
java·开发语言·excel
pangtao202516 分钟前
【瑞萨RA × Zephyr评测】看门狗
java·后端·spring
mini_05527 分钟前
elementPlus版本升级,el-select默认值显示问题
前端·javascript·vue.js
HappyBoy_201928 分钟前
MybatisPlus IPage分页查询工具类
java·开发语言
键来大师31 分钟前
Android16 AP热点修改默认密码为12345678
android·framework·rk3576·android16
小徐Chao努力34 分钟前
【Langchain4j-Java AI开发】10-框架集成(Spring Boot & Quarkus)
java·人工智能·spring boot
李坤林36 分钟前
Android KGI (Generic Kernel Image)
android