ToggleButton

PDF for offline use
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-10

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 known 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:

Examples of Switches and ToggleButtons in both on and off states

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

  1. Open the Resources/layout/Main.axml file and add the ToggleButton element (inside the LinearLayout):

  2. 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.

  3. 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.

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.