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

相关推荐
吃饺子不吃馅11 分钟前
root.render(<App />)之后 React 干了哪些事?
前端·javascript·面试
SimonKing12 分钟前
Archery:开源、一站式的数据库 SQL 审核与运维平台
java·后端·程序员
鹏多多21 分钟前
基于Vue3+TS的自定义指令开发与业务场景应用
前端·javascript·vue.js
江城开朗的豌豆29 分钟前
Redux 与 MobX:我的状态管理选择心路
前端·javascript·react.js
吃饺子不吃馅1 小时前
✨ 你知道吗?SVG 里藏了一个「任意门」——它就是 foreignObject! 🚪💫
前端·javascript·面试
前行的小黑炭2 小时前
【Android】 Context使用不当,存在内存泄漏,语言不生效等等
android·kotlin·app
前行的小黑炭3 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
gnip9 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
掘金安东尼11 小时前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
皮皮林55112 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea