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

相关推荐
小小寂寞的城21 分钟前
JAVA观察者模式demo【设计模式系列】
java·观察者模式·设计模式
coding随想42 分钟前
JavaScript中的系统对话框:alert、confirm、prompt
开发语言·javascript·prompt
探索java1 小时前
Java并发编程中的StampedLock详解:原理、实践与性能优化
java·stampedlock
界面开发小八哥1 小时前
「Java EE开发指南」如何用MyEclipse将Java项目转换为Web项目?
java·ide·java-ee·eclipse·开发工具·myeclipse
pobu1681 小时前
aksk前端签名实现
java·前端·javascript
0wioiw01 小时前
Flutter基础(前端教程⑤-组件重叠)
开发语言·前端·javascript
人生游戏牛马NPC1号1 小时前
学习 Flutter (一)
android·学习·flutter
冰天糖葫芦2 小时前
VUE实现数字翻牌效果
前端·javascript·vue.js