android - 选择其他单选按钮时,单选按钮组中的单选按钮不会取消选择
问题描述
我有以下使用单选按钮组动态添加单选按钮的 xml。
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/list_item_sort_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="@+id/rbSortOptionGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是在对话框片段中,用户将选择一个单选按钮并单击应用将关闭对话框。
当用户再次打开对话框片段时,单选按钮的先前状态将被自动选中。但是,在选择另一个单选按钮后,保存的单选按钮将保持选中状态,因此我总是同时选择 2 个单选按钮。
选择其他单选按钮时有没有办法取消选择它。
这是我动态创建单选按钮并将它们添加到单选组时的课程。
@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()
listOfTopsProductSort.forEach { topsProductSort ->
val materialRadioButton = MaterialRadioButton(context)
materialRadioButton.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.black)))
materialRadioButton.text = topsProductSort.name
materialRadioButton.tag = TopsProductSort(code = topsProductSort.code, name = topsProductSort.name)
materialRadioButton.isChecked = topsProductSort.isSelected // Set the previous radio button that was selected
materialRadioButton.clicks()
.debounce(250L, TimeUnit.MILLISECONDS)
.observeOn(schedulersFacade.ui)
.map {
materialRadioButton.tag as TopsProductSort
}
.subscribeBy(
onNext = { _topsProductSort ->
if (materialRadioButton.tag is TopsProductSort) {
tapSortButtonRelay.accept(_topsProductSort.copy(isSelected = true))
}
},
onError = {
Timber.e(it.localizedMessage)
}
)
rbSortOptionGroup.addView(materialRadioButton)
}
}
}
解决方案
为了在以编程方式创建时避免这种行为,MaterialRadioButton
您需要@+id
为每个设置一个唯一标识符,MaterialRadioButton
以便RadioGroup
可以在其选择/取消选择阶段识别其每个子项。为此,您可以使用ViewCompat.generateViewId()
以编程方式生成唯一 ID。
在创建每个过程中,MaterialRadioButton
您可以使用上述方法,如下所示:
val materialRadioButton = MaterialRadioButton(context)
materialRadioButton.id = ViewCompat.generateViewId()
通过执行上述操作,RadioGroup
将能够唯一标识其每个子节点,并将充当单一选择。
推荐阅读
- c# - 当前上下文中不存在名称“猫”
- unity3d - 如何在 Unity Mapbox World Scale 中添加碰撞物理?
- reactjs - 如何修复该 fetchmetadata:sill resolvewithnewmodule react-is@16.8.6 检查可安装
- android - 谷歌云端点框架与 Android Studio 和 gradle 5.1.1 不兼容
- vhdl - 从文件中读取矩阵
- sql - 使用日期之间的减法来处理“order by”的问题(其中一个来自查询)
- css - 用于电子邮件格式的媒体查询不起作用
- asp.net-core - 如何使用本地 ADFS 验证和获取 ASP .NET CORE WEB API 应用程序的令牌?
- c++ - 行为:内存操作错误或内存泄漏 C++
- image - 提高 28 x 28 像素图像中单个字母识别的建议