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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With