Radio button not showing selected by default while orientation change

46 views Asked by At

I added a RadioGroup which contains 3 RadioButtons and by default first one should be selected so added android:checked="true" in xml. Now when device orientation getting changed to horizontal radio1 stops showing checked and tapping on it doesn't make any changes. Currently not handling any device orientation state so it should recreate the layout. Is it an android radio-group bug?

Below is the xml code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:checked="true"
            android:text="Radio 1" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Radio 2" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Radio 3" />

    </RadioGroup>

</androidx.constraintlayout.widget.ConstraintLayout>

Issue Video:

https://imgur.com/a/4Y903er

How to recreate issue: Tap on Radio 2 or Radio 3 > Rotate device > Since activity recreated it is expected Radio 1 should show checked but it is not showing and even on tap not changed to checked.

1

There are 1 answers

0
Vinay On

When the device orientation changes, the activity is recreated, and the state of the views needs to be saved and restored manually. To fix this issue can use viewmodel and store the state in ViewModel or another way save the radiobutton state on onSaveInstanceState and restore them on onRestoreInstanceState when activity recreated.

override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("selectedButtonId", radioGroup.checkedRadioButtonId)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        val selectedButtonId = savedInstanceState.getInt("selectedButtonId")
        radioGroup.check(selectedButtonId)
    }

for more details follow : https://developer.android.com/guide/fragments/saving-state