首页 > 解决方案 > Android单选按钮多选

问题描述

长话短说。我正在单选组内创建单选按钮。我将根据用户选择的内容对我的表进行过滤。我默认选中了一个单选按钮。因此,当我尝试检查其他按钮时,它会保持选中状态。事实上,这两个按钮都被检查了。太奇怪了。也许这是因为我以编程方式做所有事情。设计仍在进行中。我只是停在这里,因为我不知道这是否是视觉错误。我正在使用 Kotlin 进行 Android 开发。

显示按钮:

    private fun displayChoices(choices: List<FiltersList.Choice>, multipleChoice: Boolean) {
        val radioGroup = RadioGroup(this)
        for (choice in choices) {
            val button = if (multipleChoice) {
                CheckBox(this)
            } else {
                RadioButton(this)
            }

            button.apply {
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT).apply {
                    setMargins(16, 8, 16, 8)
                }
                text = choice.display
                isChecked = choice.selected
                setTextColor(ResourcesCompat.getColor(resources, R.color.colorTextClicked, null))
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    buttonTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, R.color.colorButton, null))
                }
            }
            radioGroup.addView(button)
        }
        filters_content.addView(radioGroup)
    }

我的布局:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/colorFilterBoxBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FilterDialogActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/filters_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:orientation="vertical">

        </LinearLayout>

    </ScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

风景: 问题看起来像这样

我以编程方式选择任何日期按钮并保持选中状态。我从服务器获取数据,默认情况下需要选择哪些项目。

标签: androidkotlinradio-buttonradio-group

解决方案


好的,起初我认为这是因为您在 radioGroup 中设置了其他视图,因为 radioButtons 需要是直接子级。但这里不是这种情况,问题是在以编程方式在 radioGroup 内创建单选按钮时,您需要为每个单选按钮分配特定的 id。

没有找到文档,但我猜 radioGroup 使用按钮 id 来实现互斥。如此简单的解决方案id为您正在创建的每个单选按钮设置一个至于您使用的 id,这是文档中提到的。

标识符在此视图的层次结构中不必是唯一的。标识符应该是一个正数。

如果它在 Java 中,您可以使用button.setId(choices.indexOf(choice)+1001);. 我对 Kotlin 不太好,但我想 Kotlin 的等价物是

id = choices.indexOf(choice) + 1001 //where 1001 i just a random int I used to try avoid conflict

为按钮设置一个 ID,这应该可以解决您的问题。祝你好运。


推荐阅读