Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 298
Leone Avatar asked May 22 '18 08:05

Leone


2 Answers

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

like image 64
Anthony Cannon Avatar answered Nov 05 '22 13:11

Anthony Cannon


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.

like image 24
Ali bana Avatar answered Nov 05 '22 13:11

Ali bana