当前位置: 首页 > news >正文

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() {@Overridepublic 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() {@Overridepublic 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互斥的功能。

http://www.lryc.cn/news/370408.html

相关文章:

  • 如何在ElementTree文本中嵌入标签
  • C语言宏定义+条件编译
  • python实现自动化测试框架如何进行数据参数化?这个包可以了解下
  • 面试题:Redis和MySql数据库如何保持数据一致性?
  • 直流遥控器 继电器8-10V应用 降压恒压SL3036电源芯片
  • 论文Abstract怎么写
  • PS系统教程19
  • Excel函数之MAP
  • 在2024年WWDC大会上,苹果宣布了其全新的“Apple Intelligence”AI功能以及ISO18功能
  • 解决linux jenkins要求JDK版本与项目版本JDK不一致问题
  • 推荐一款WPF绘图插件OxyPlot
  • 普通表在线重定义为分区表
  • 自动驾驶场景下TCP协议参数优化调整案例分享
  • 奇思妙想:多头RAG
  • H323 截包分析辅流问题
  • 低成本和颜值兼顾的 HomeLab 设备:HPE MicroServer Gen10(二)
  • 面试题:ArrayList和LinkedList的区别
  • 【王树森】深度强化学习(DRL)学习笔记
  • LLM应用实战:当图谱问答(KBQA)集成大模型(三)
  • Django框架中Ajax GET与POST请求的实战应用
  • web前端怎么挣钱, 提升技能,拓宽就业渠道
  • 基于Python的信号处理(包络谱,低通、高通、带通滤波,初级特征提取,机器学习,短时傅里叶变换)及轴承故障诊断探索
  • 大型语言模型智能体(LLM Agent)在实际使用的五大问题
  • C语言内存管理
  • AD24设计步骤
  • 基于MBD的大飞机模块化广域协同研制
  • 鸿蒙轻内核M核源码分析系列二十 Newlib C
  • 力扣1818.绝对差值和
  • 矩阵练习2
  • 2024海南省大数据教师培训-Hadoop集群部署