我有以下的 XML,它使用单选按钮组在运行时动态地添加单选按钮。
一旦布局被填充,它看起来像这样:
这是在Dialog fragment中,用户将选择一个单选按钮并单击“应用”以关闭对话框。
当用户再次打开对话框片段时,单选按钮的先前状态将自动选择。然而,在选择另一个单选按钮之后,保存的单选按钮仍将保持选中状态,因此我总是同时有2个单选按钮被选中。
是否有方法在选择其他单选按钮时取消选择此单选按钮?
这是我创建单选按钮并将它们添加到单选按钮组的类。
<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>
一旦布局被填充,它看起来像这样:
![Radio buttons](https://istack.dev59.com/YRtof.webp)
当用户再次打开对话框片段时,单选按钮的先前状态将自动选择。然而,在选择另一个单选按钮之后,保存的单选按钮仍将保持选中状态,因此我总是同时有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)
}
}
}