How to get the selected index of a RadioGroup in Android

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" />
</RadioGroup>

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


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 contains other Views (like a TextView) then the indexOfChild() method will return wrong index.

To get the selected RadioButton text on the RadioGroup:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

This should work,

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));