Toggle Button

A button used specifically for toggling something on and off.

1. Open the layout file and, inside the LinearLayout, add the ToggleButton element:

<ToggleButton android:id="@+id/togglebutton" android:layout width="wrap content" android:layout height="wrap content" />

final ToggleButton togglebutton = (ToggleButton) findViewById(;

togglebutton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// Perform action on clicks if (togglebutton.isChecked()) {

Toast.makeText(HelloFormStuff.this, "ON", Toast.LENGTH_SHORT).show();

Toast.makeText(HelloFormStuff.this, "OFF",

This captures our ToggleButton element from the layout, then adds an on-click listener to it. The View.OnClickListener must define the onClick() method, which defines the action to be made when the button is clicked. Here, we query the current state of the ToggleButton, then pop up a Toast message that displays the current state. Notice that the ToggleButton handles its own state change between checked and un-checked, so we just ask which it is. 3. Run it.

Tip: By default, the text on the button is "ON" and "OFF", but you can change each of these with setTextOn( CharSequence) and setTextOff( CharSequence) . And, if you find that you need to change the state in another way (such as when loading a saved CheckBoxPreference), use setChecked(true) or toggle().

If you've added all the form items above, your application should look something like this:


ImageButton EditText CheckBox RadioButton


Was this article helpful?

0 0

Post a comment