Android SDK: How To Use The Toggle Button

There are two types of buttons in the Android SDK: regular buttons and toggle buttons. We could do without toggle buttons but it would require more programming than necessary. In this tutorial you will learn to check the state of a toggle button.

toggle button showing off state and toast message

the toggle button with a message displaying its state

Making The Toggle Button

The toggle button requires the use of the ToggleButton tag. Let’s make a button that is centered on the screen, the button will call a function called toggle() on click.

layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
	android:id="@+id/relativeLayout1" 
	android:layout_height="fill_parent"
	android:layout_weight="0.72" xmlns:android="http://schemas.android.com/apk/res/android">
	<ToggleButton 
	android:id="@+id/toggleButton" 
	android:layout_width="200px" 
	android:layout_height="100px" 
	android:layout_centerVertical="true" 
	android:layout_centerHorizontal="true"
	android:onClick="toggle"></ToggleButton>
</RelativeLayout>

You can also change the on and off text of the button by adding the following attributes to the ToggleButton tag:

	android:textOn="close"
	android:textOff="open"

Handling The Clicks

toggle button in on state with message

app behavior when the button is toggled on, a similar effect takes place when it's toggled off

All we need to do is check the isChecked() method of the toggle button object inside our toggle() function. The following code does the checking and also raises a toast with the state of the button.

TestActivity.java
package com.yoursite.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class TestActivity extends Activity {
	TextView msg;
	private ToggleButton buttonLED;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		buttonLED = (ToggleButton) findViewById(R.id.toggleButton);
	}

	public void toggle(View v){
		if(buttonLED.isChecked())
			Toast.makeText(TestActivity.this, "the button is ON", Toast.LENGTH_SHORT).show();
		else
			Toast.makeText(TestActivity.this, "the button is OFF", Toast.LENGTH_SHORT).show();
	}

}

Related posts: