本文主要是介绍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互斥的功能。
这篇关于Android - RadioGroup中多个radiobutton同时被选中问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!