[java] 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.

This question is related to java android xml radio-group

The answer is


 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));

radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);

  btnDisplay=(Button)findViewById(R.id.button);

  btnDisplay.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        int selectedId=radioSexGroup.getCheckedRadioButtonId();
        radioSexButton=(RadioButton)findViewById(selectedId);
        Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
     }
  });

All you need is to set values first to your RadioButton, for example:

RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
radioButton.setId(1);        //some int value

and then whenever this spacific radioButton will be chosen you can pull its value by the Id you gave it with

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                       //should be inside the "radioGroup"
                                                       //in the XML

Cheers!


You could have a reference to the radio group and use getCheckedRadioButtonId () to get the checked radio button id. Take a look here

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

Then when you need to get the selected radio option.

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}

Kotlin:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)

It worked perfectly for me in this way:

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();

you can do

findViewById

from the radio group .

Here it is sample :

((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);

You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()


radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
        }
    });

try this

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

This should work,

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

You can simply

-declare the radio group and a radio button out of onCreate method

private RadioGroup GrupName;
private RadioButton NameButton;

-set the view id in the onCreate method

GrupName = (RadioGroup) findViewById(R.id.radioGroupid);

-take the radiobutton id selected using

int id = GroupName.getCheckedRadioButtonId();

-use the id to match the buttonselected view

NameButton = (RadioButton) findViewById(id);

-finally get the value of the radio button

String valueExpected = NameButton.getText().toString();

--- PS: IF YOU WANT AN INT VALUE, THEN YOU CAN CAST IT

int valueExpectedIn = Integer.parseInt(valueExpected);

Late to the party, but here is a simplification of @Tarek360's Kotlin answer that caters for RadioGroups that might contain non-RadioButtons:

    val RadioGroup.checkedIndex: Int
        get() = children
            .filter { it is RadioButton }
            .indexOfFirst { it.id == checkedRadioButtonId }

If you're RadioFroup definitely only has RadioButtons then this can be a simple as:

    private val RadioGroup.checkedIndex = 
        children.indexOfFirst { it.id == checkedRadioButtonId }

Then you don't have the overhead of findViewById.


//use to get the id of selected item

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//get the view of the selected item

View selectedView = (View)findViewById( selectedID);

Here is a Kotlin extension to get the correct position even if your group contains a TextView or any non-RadioButton.

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

just use this:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to radio-group

Multiple radio button groups in one form How to check if a radiobutton is checked in a radiogroup in Android? Multiple radio button groups in MVC 4 Razor AngularJs: How to set radio button checked based on model How to set radio button checked as default in radiogroup? How to set OnClickListener on a RadioButton in Android? RadioGroup: How to check programmatically How to get the selected index of a RadioGroup in Android