Android Widget – RadioButton & RadioGroup

android radiogroup

In Android, you can use “android.widget.RadioButton” class to render radio button, and those radio buttons are usually grouped by
android.widget.RadioGroup. If RadioButtons are in group, when one RadioButton within a group is selected, all others are automatically deselected.

Open “your.xml” file, just add “RadioGroup”, “RadioButton” and a button, inside the LinearLayout.

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
    <radiogroup android:id="@+id/radioSex" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <radiobutton android:id="@+id/radioMale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_male" android:checked="true">
        <radiobutton android:id="@+id/radioFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_female">
    </radiobutton></radiobutton></radiogroup>
    <button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_display">
//To make a radio button is selected by default, put android:checked="true" within the RadioButton element.
// In this case, radio option "Male" is selected by default.</button></linearlayout>

Inside activity “onCreate()” method, attach a click listener on button.

public class MainActivity extends Activity {
  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    addListenerOnButton();
  }
  public void addListenerOnButton() {
    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(MyAndroidAppActivity.this,
                radioSexButton.getText(), Toast.LENGTH_SHORT).show();
        }
    });
  }
}