askIT

Android Get selected radio button

media-floppy.png Download android_radio_buttons_male_female.zip

Radio buttons has to be grouped togheter in a radio group. If we want to create a radio group where the user selects between male and female the layout should look like this:

android_radio_button_male_female_xml.png

Android XML design code:

<RadioGroup
    android:id="@+id/radioGroupGender"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioButton
        android:id="@+id/radioButtonGenderMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="@string/male"
        android:layout_marginRight="5dp"/>

    <RadioButton
        android:id="@+id/radioButtonGenderFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/female" />
</RadioGroup>

Get id value (0 or 1)

/* Radiogroup Get id value (0 or 1) */
RadioGroup radioGroupGender = (RadioGroup)findViewById(R.id.radioGroupGender);
int radioButtonID = radioGroupGender.getCheckedRadioButtonId(); // get selected radio button from radioGroup
View viewGender = radioGroupGender.findViewById(radioButtonID);
int positionGender = radioGroupGender.indexOfChild(viewGender); // If you want position of Radiobutton

String stringGender = "";
if(positionGender == 0){
        stringGender = "male";
}
else{
        stringGender = "female";
}

Toast.makeText(this, "radioGetId()\nPosition: " + positionGender + "\nString: " + stringGender, Toast.LENGTH_LONG).show();

Get text value (Male or Female)

/* Radiogroup Get text value (Male or Female) */
RadioGroup radioGroupGender = (RadioGroup)findViewById(R.id.radioGroupGender);
int radioGenderSelectedId = radioGroupGender.getCheckedRadioButtonId(); // get selected radio button from radioGroup
RadioButton radioButtonGender = (RadioButton) findViewById(radioGenderSelectedId); // find the radiobutton by returned id
String stringGender = radioButtonGender.getText().toString();
Toast.makeText(this, stringGender, Toast.LENGTH_LONG).show();


Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.