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

2

6

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.

Radio buttons with one of them that can't be unchecked

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.

Eure answered 22/5, 2018 at 8:19 Comment(2)
Are you using the kotlin-kapt plugin? (Just so I know what to use in my answer)Sergiosergipe
@AnthonyCannon No. Just plain kotlin.Eure
S
9

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

Sergiosergipe answered 22/5, 2018 at 9:34 Comment(3)
Thanks man. The index in radioGroup.check call is rather the radio button Id. In addition to that, I had to do the radioGroup.check(index) call after adding all the radio buttons.Eure
Ah yes, my mistake. Ill update my answer. Glad I can help.Sergiosergipe
my bad, I was doing radioButton.isSelected = ... It is isChecked insteadBalmung
R
4

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.

Remissible answered 22/5, 2018 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.