Android ToggleButton Example

By | October 21, 2013
Android SDK Provides “android.widget.ToggleButton” class to create a special kind of button called togglebutton .

A togglebutton simply has two types of state “ON” or “OFF” with a with a “light” indicator .

In this tutorial we will see how to add togglebutton to the activity and also check the state of the togglebutton wheather it is “ON” or “OFF” by using “OnCheckedChangeListener

Android Toggle Button OffAndroid Toggle Button On


Lets See An Example

Project Detail

Project Name ToggleButtonDemo
Package com.pavan.togglebuttondemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

 1. XML Layout

  file :- activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >

<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Button State :"
android:textSize="20dp" />

<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="20dp" />

</LinearLayout>

 2. Activity

  file :- MainActivity.java

package com.pavan.togglebuttondemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

ToggleButton toggle_btn;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toggle_btn = (ToggleButton) findViewById(R.id.toggleButton1);
tv = (TextView) findViewById(R.id.textview2);

toggle_btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

if (isChecked) {
tv.setText("ON");
} else {
tv.setText("OFF");
}

}
});
}
}