Android RadioGroup内动态添加RadioButton选中新项时旧项无法取消选中问题
问题原因
出现多选项同时选中的核心原因是RadioGroup的单选逻辑没有正常触发,具体有3个常见诱因:
- 动态创建的RadioButton没有设置唯一ID,RadioGroup依赖子View的ID来管理选中状态,无ID时无法正确追踪和取消旧选中项
- 单独给每个RadioButton设置点击事件修改选中状态,和RadioGroup原生的单选逻辑冲突
- 子View还未添加到RadioGroup时就单独设置
isChecked属性,RadioGroup无法感知该操作,不会同步取消其他项的选中状态
解决方案
按照以下步骤修改代码即可恢复单选逻辑:
- 每个动态创建的MaterialRadioButton生成唯一ID,可使用系统提供的
View.generateViewId()方法 - 移除单个RadioButton的点击监听,统一监听RadioGroup的选中变化事件
- 所有RadioButton添加到RadioGroup后,统一调用RadioGroup的
check()方法设置默认选中项,不要单独给子View设置isChecked
修改后的代码示例
@EpoxyModelClass(layout = R.layout.list_item_sort_item) abstract class SortItemModel(private val schedulersFacade: SchedulersFacade) : EpoxyBaseModel() { @EpoxyAttribute lateinit var listOfTopsProductSort: List<TopsProductSort> @EpoxyAttribute lateinit var tapSortButtonRelay: PublishRelay<TopsProductSort> override fun bind(holder: EpoxyBaseViewHolder) { with(holder.itemView) { rbSortOptionGroup.removeAllViews() // 先清除旧的监听避免重复回调 rbSortOptionGroup.setOnCheckedChangeListener(null) var defaultCheckedId = -1 // 存储id和对应排序项的映射 val idToSortMap = mutableMapOf<Int, TopsProductSort>() listOfTopsProductSort.forEachIndexed { index, topsProductSort -> val materialRadioButton = MaterialRadioButton(context) // 生成唯一ID val viewId = View.generateViewId() materialRadioButton.id = viewId materialRadioButton.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.black))) materialRadioButton.text = topsProductSort.name val sortItem = TopsProductSort(code = topsProductSort.code, name = topsProductSort.name) materialRadioButton.tag = sortItem idToSortMap[viewId] = sortItem // 记录默认选中的ID if (topsProductSort.isSelected) { defaultCheckedId = viewId } rbSortOptionGroup.addView(materialRadioButton) } // 所有子View添加完成后设置选中监听和默认选中项 rbSortOptionGroup.setOnCheckedChangeListener { _, checkedId -> idToSortMap[checkedId]?.let { selectedSort -> tapSortButtonRelay.accept(selectedSort.copy(isSelected = true)) } } if (defaultCheckedId != -1) { rbSortOptionGroup.check(defaultCheckedId) } } } }
内容的提问来源于stack exchange,提问作者ant2009
相关产品推荐
相关产品推荐

