Cross Platform
Android
iOS
Mac

ToggleButton

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. Both the ToggleButton and the Switch are descendants of the CompoundButton class and so as such they

An example of a ToggleButton can be seen in the left hand image, while the right hand image is an example of a Switch:
  

Which control an application uses is a matter of style. Both widgets are functionally equivalent.

  1. Open the Resource\layout\main.xml file and add the ToggleButton element (inside the LinearLayout):
  2. <ToggleButton android:id="@+id/togglebutton"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:textOn="Vibrate on"
                          android:textOff="Vibrate off"/>

    The code for displaying a switch is very similiar:

    <Switch android:id="@+id/togglebutton"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:textOn="Vibrate on"
                       android:textOff="Vibrate off"/>

    The attributes android:textOn and android:textOff specify the text for the button when the button has been toggled on or off. The default values are "ON" and "OFF".

  3. 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 ToggleButton element 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 a Toast message that indicates the current state.

    Notice that the ToggleButton handles its own state change between checked and unchecked, so you just ask which it is.

  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. This tutorial is based on the Android Form Stuff tutorial.