gpt4 book ai didi

android - 选择其他单选按钮时,单选按钮组中的单选按钮不会取消选择

转载 作者:行者123 更新时间:2023-12-04 23:55:46 24 4
gpt4 key购买 nike

我有以下使用单选按钮组动态添加单选按钮的 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>
一旦布局膨胀,它看起来像这样:
Radio buttons
这是在对话框 fragment 中,用户将选择一个单选按钮并单击应用将关闭对话框。
当用户再次打开对话框 fragment 时,单选按钮的先前状态将被自动选中。但是,在选择另一个单选按钮后,保存的单选按钮将保持选中状态,因此我总是同时选择 2 个单选按钮。
选择其他单选按钮时有没有办法取消选择它。
这是我动态创建单选按钮并将它们添加到单选组时的类(class)。
@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可以在其选择/取消选择阶段识别其每个 child 。为此,您可以使用 ViewCompat.generateViewId()以编程方式生成唯一 ID。
在创建每个 MaterialRadioButton您可以使用上述方法,如下所示:

val materialRadioButton = MaterialRadioButton(context)
materialRadioButton.id = ViewCompat.generateViewId()
通过执行上述 RadioGroup将能够唯一标识其每个子项,并将作为单一选择。

关于android - 选择其他单选按钮时,单选按钮组中的单选按钮不会取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69885491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com