Friday, 31 May 2013

Android Toggle ButtonsA toggle button allows the user to change a setting between two states.

You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.

Toggle Button Click Event

To define the click event handler, add the android:onClick attribute to the <ToggleButton> or <Switch>element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

Within the Activity that hosts this layout, the following method handles the click event:

<ToggleButton

android:id="@+id/togglebutton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="onToggleClicked"

android:textOff="Sound off"

android:textOn="Sound on"/>

Within the Activity that hosts this layout, the following method handles the click event:

publicvoid
onToggleClicked(View view) {

// Is the toggle on?

boolean
on = ((ToggleButton)
view).isChecked();

if
(on) {

// Enable Sound

} else
{

// Disable Sound

}

}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

In this tutorial, we show you how to use XML to create two toggle buttons and a normal button, when user click on the normal button, it will display the current state of both toggle buttons.