首页 > 解决方案 > Android Anko Radio Group 的默认值?

问题描述

我正在用 Kotlin 和 Anko 编写一个 android 应用程序,我正在尝试为单选按钮设置一个默认值,但是当我这样做时,该值永远不会被取消选中。当您单击其他地方时,如何设置更改的默认值?

radioGroup {
    orientation = LinearLayout.HORIZONTAL
    bottomPadding = dip(8)

    val radBut = { value: Int ->
        radioButton {
            text = "$value"
            onClick { Store.playerCount = value }
            if (Store.playerCount == value) {
                isChecked = true
            }
            rightPadding = dip(8)
        }
    }

    (2..5).map { radBut(it) }
}

标签: androidkotlinanko

解决方案


不要直接更改单选按钮的 isChecked 属性,而是让单选按钮组通过将单选按钮 id 提供给单选按钮组检查(int id)方法来处理它,请查看此链接以获取更多详细信息https://developer.android.com/reference/ android/widget/RadioGroup#check(int) 这是给你的代码

   verticalLayout {
        orientation = LinearLayout.VERTICAL

        radioGroup {
            orientation = LinearLayout.HORIZONTAL
            padding = dip(8)

            val button1 = radioButton {
                text = "Button 1"
            }

            radioButton {
                text = "Button 2"
            }

            radioButton {
                text = "Button 3"
            }

            // Checking button 1 as default
            check(button1.id)
        }
    }

推荐阅读