Android get value of the selected radio button

Totti picture Totti · Jun 25, 2012 · Viewed 85.1k times · Source

I have a RadioGroup rg1 and I want to get the value of the selected radio button.

I know that I can get the id of the selected radio button by using:

if(rg1.getCheckedRadioButtonId()!=-1)
int id= rg1.getCheckedRadioButtonId()

that gives me the id , but I want the value of that button.

Answer

Otra picture Otra · Jun 25, 2012

You need to get the radio button at that index, then get the value of the text of that button. Try this code below.

if(rg1.getCheckedRadioButtonId()!=-1){
    int id= rg1.getCheckedRadioButtonId();
    View radioButton = rg1.findViewById(id);
    int radioId = radioGroup.indexOfChild(radioButton);
    RadioButton btn = (RadioButton) rg1.getChildAt(radioId);
    String selection = (String) btn.getText();
}