简体   繁体   中英

Android checking radio button in code makes it stay checked in a radiogroup

I have a dynamically added radio buttons in a RadioGroup . And I have to check one of them in code based on some data.

Now, the issue is after the radio buttons are shown and the user checks on another radio button in the same group, the previously selected radio is still checked ... resulting in two checked RadioButtons .

其中一个不能取消选中的单选按钮

This is how I am rendering the buttons in Kotlin:

val rg = RadioGroup(this).apply { orientation = RadioGroup.HORIZONTAL }
choices.values.forEach { c ->
    rg.addView(RadioButton(this).apply {
        tag = someTag
        text = c
        isChecked = answer.equals(c) // condition
    })
}

The strange thing is it all works fine if no RadioButton is checked programmatically.

Instead of setting radioButton.isChecked = ... . Try using the radioGroup.check(id) .

I use this code for RadioButton.

radio_rg.setOnCheckedChangeListener { _, checkedId ->
    val radio: RadioButton = findViewById(checkedId)
    when (radio) {
        radioBtn1 -> {
            // some code
        }
        radioBtn2 -> {
             // some code
        }
    }
}

Hope this helps you.

About no RadioButton being checked, I've never tried it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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