RadioButton
- PDF for offline use
Let us know how you feel about this
Translation Quality
0/250
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.
Open the Resources/layout/Main.axml file and add two
RadioButtons, nested in aRadioGroup(inside theLinearLayout):<RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/radio_red" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Red" /> <RadioButton android:id="@+id/radio_blue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Blue" /> </RadioGroup>It's important that the
RadioButtons are grouped together by theRadioGroupelement so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When oneRadioButtonwithin a group is selected, all others are automatically deselected.To do something when each
RadioButtonis 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
Toastmessage displays the selected radio button's text.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.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.
Let us know how you feel about this
Translation Quality
0/250
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.

