Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.9k points)

Is there an easy way to get the selected index of a RadioGroup in Android or do I have to use OnCheckedChangeListener to listen for changes and have something that holds the last index selected?

example xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">

    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />

    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />

    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />

    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />

    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />


if a user selects option 3 I want to get the index, 2.

1 Answer

0 votes
by (46k points)

You should be able to do something like this:

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();

View radioButton = radioButtonGroup.findViewById(radioButtonID);

int idx = radioButtonGroup.indexOfChild(radioButton);

If the RadioGroup includes other Views (like a TextView) then the indexOfChild() program will return the wrong index.

To get the selected RadioButton text on the RadioGroup:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);

 String selectedtext = r.getText().toString();

Related questions

0 votes
1 answer
asked Oct 31, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories