PDF for offline use

Let us know how you feel about this

Translation Quality


last updated: 2017-04

In this section, you will create two mutually-exclusive radio buttons (enabling one disables the other), using the RadioGroup and RadioButton widgets. When either radio button is pressed, a toast message will be displayed.

  1. Open the Resources/layout/Main.axml file and add two RadioButtons, nested in a RadioGroup (inside the LinearLayout):

          <RadioButton android:id="@+id/radio_red"
              android:text="Red" />
          <RadioButton android:id="@+id/radio_blue"
              android:text="Blue" />

    It's important that the RadioButtons are grouped together by the RadioGroup element so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When one RadioButton within a group is selected, all others are automatically deselected.

  2. To do something when each RadioButton is selected, we need to write an event handler:

    private void RadioButtonClick (object sender, EventArgs e)
        RadioButton rb = (RadioButton)sender;
        Toast.MakeText (this, rb.Text, ToastLength.Short).Show ();

    First, the sender that is passed in is cast into a RadioButton. Then a Toast message displays the selected radio button's text.

  3. Now, at the bottom of the OnCreate() method, add the following:

    RadioButton radio_red = FindViewById<RadioButton>(Resource.Id.radio_red);
    RadioButton radio_blue = FindViewById<RadioButton>(Resource.Id.radio_blue);
    radio_red.Click += RadioButtonClick;
    radio_blue.Click += RadioButtonClick;

    This captures each of the RadioButtons from the layout and adds the newly-created event handlerto each.

  4. Run the application.

Tip: If you need to change the state yourself (such as when loading a saved CheckBoxPreference), use the Checked property setter or Toggle() method.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.