ToggleButton
- PDF for offline use
- Related SDKs:
Let us know how you feel about this
Translation Quality
0/250
last updated: 2017-04
In this section, you'll create a button used specifically for toggling
between two states, using the
ToggleButton widget. This
widget is an excellent alternative to radio buttons if you have two
simple states that are mutually exclusive ("on" and "off", for
example). Android 4.0 (API level 14) introduced an alternative to the
toggle button know as a
Switch.
An example of a ToggleButton can be seen in the left hand pair of images, while the right hand pair of images presents an example of a Switch:
Which control an application uses is a matter of style. Both widgets are functionally equivalent.
Open the Resources/layout/Main.axml file and add the
ToggleButtonelement (inside theLinearLayout):To do something when the state is changed, add the following code to the end of the
OnCreate()) method:ToggleButton togglebutton = FindViewById<ToggleButton>(Resource.Id.togglebutton); togglebutton.Click += (o, e) => { // Perform action on clicks if (togglebutton.Checked) Toast.MakeText(this, "Checked", ToastLength.Short).Show (); else Toast.MakeText(this, "Not checked", ToastLength.Short).Show (); };This captures the
ToggleButtonelement from the layout, and handles the Click event, which defines the action to perform when the button is clicked. In this example, the method checks the new state of the button, then shows aToastmessage that indicates the current state.Notice that the
ToggleButtonhandles its own state change between checked and unchecked, so you just ask which it is.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.
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.

