繁体   English   中英

Android 单选按钮多个 select

[英]Android radio button multiple select

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

风景: 问题看起来像这样

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

好吧,一开始我以为这是因为你在 radioGroup 中设置了其他视图,因为 radioButtons 需要是一个直接的孩子。 但这里的情况并非如此,问题是当以编程方式在 radioGroup 中创建 radioButtons 时,您需要为每个 radioButton 分配特定的 id。

没有找到文档,但我猜 radioGroup 使用按钮 ID 来实现互斥。 如此简单的解决方案为您正在创建的每个 radioButton 设置一个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,这应该可以解决您的问题。 祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM