How to get the selected index of a RadioGroup in Android
Asked Answered
C

19

236

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.

Coverage answered 22/6, 2011 at 12:58 Comment(0)
T
517

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();
Tenner answered 22/6, 2011 at 13:58 Comment(5)
But what if those buttons do not have their android:id attributes set?Antistrophe
@BP i have same doubt in accessing radio buttons when none of the parent or the radio buttons id is set.Ointment
@Antistrophe As long as you do radioGroup.findViewById(radioButtonID) it'll work. RadioGroup does set 1, 2, 3, 4, and so on as view's IDs, so if you do search for them within it's context, it'll workShavonda
This not working if default (and untouched by User) RadioButton is setted.Derma
@NinjaCoding If you made the same mistake as me, you have to set the default (initial) radio button by calling radioGroup.check(selectedRadioButton.id), not radioButton.setChecked(true).Odonnell
K
117

This should work,

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
Kerrikerrie answered 22/6, 2011 at 14:6 Comment(1)
Use getActivity().findViewById() if you are using in the Fragment.Stilton
E
56

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
    }
}
Earnestineearnings answered 22/6, 2011 at 13:11 Comment(8)
yes, this is the id of the checked radio button, but what about the index of the radio button in the radio group?Coverage
i can get the id, i want the index, they are different.Coverage
what do you mean by index? is it in a list view?Earnestineearnings
if i have 5 radiobuttons in the radiogroup, and the user selects the 3rd one i want to get 2, the index of the selected radiobutton in the radiogroup. this is not a listview.Coverage
just to clarify if the user selects the 3rd button you want to get the 2nd one? radio groups and buttons do not have indexes.Earnestineearnings
no, the index of the 3rd button is 2, zero based indexing. the first radio button has an index of 0, second is 1, third 2, etc... What you're saying is there's no good way to get the index, that's a valid answer too.Coverage
You could put the RadioButton in an array list and then run a search for the id and convert that into an indexEarnestineearnings
Terrible idea if you have 20+ items.Tautog
H
29

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);
            }
        });
Hermes answered 20/4, 2015 at 6:49 Comment(1)
This is works! But i can't understand why we need use this "radioButton" View..Turbulent
D
10

You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()

Discant answered 22/6, 2011 at 13:10 Comment(0)
C
9

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
Conciliator answered 6/10, 2012 at 10:23 Comment(0)
F
6

//use to get the id of selected item

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//get the view of the selected item

View selectedView = (View)findViewById( selectedID);
Flamenco answered 23/5, 2013 at 7:52 Comment(0)
C
6

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();
Cosgrave answered 28/10, 2016 at 9:16 Comment(0)
T
6

Kotlin:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)
Thermaesthesia answered 22/9, 2019 at 3:54 Comment(0)
P
5

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!

Pancreas answered 14/3, 2017 at 17:38 Comment(0)
M
5
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();
     }
  });
Moreover answered 23/7, 2017 at 13:37 Comment(0)
R
3

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.

Rutledge answered 23/8, 2020 at 10:50 Comment(1)
I posted this question 9 years ago and answers are still coming in. Have my upvote :)Coverage
U
2
 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));
Uball answered 22/12, 2014 at 14:10 Comment(0)
Z
2

just use this:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();
Zadazadack answered 27/4, 2017 at 14:7 Comment(0)
L
2

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
}
Lackey answered 7/3, 2020 at 8:42 Comment(0)
M
1

you can do

findViewById

from the radio group .

Here it is sample :

((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
Mickeymicki answered 9/9, 2015 at 4:8 Comment(0)
E
1

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);
Eighty answered 13/8, 2019 at 21:11 Comment(0)
J
0
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();
        }
    });
Jhansi answered 29/4, 2020 at 0:38 Comment(0)
C
0

You have already assigned an id for each radio button. With a case block you can detect manually the selected radio button or with OnCheckedChangeListener you get it too.

xml:

    <RadioGroup
        android:id="@+id/rd_group_pick_reason"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ti_titel"
        android:orientation="horizontal"
        android:paddingHorizontal="16dp"
        >
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_not_deliverable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_not_deliverable"
            android:checked="true"
            />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_after_pack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_after_pack"
            />
    </RadioGroup>

java:

final RadioGroup radioGroup = dialogView.findViewById(R.id.rd_group_pick_reason);    
switch (radioGroup.getCheckedRadioButtonId()) {
    case R.id.rd_not_deliverable:
        // TODO
    break;
    case R.id.rd_after_pack:
        // TODO
    break;
}

or

radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    switch (group.getCheckedRadioButtonId()) {
        case R.id.rd_not_deliverable:
            System.out.println("not deliverable");
            break;
        case R.id.rd_after_pack:
            System.out.println("after pack");
            break;
    }
Ciliate answered 7/10, 2021 at 7:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.