Android Projects

Android Development Books


Toggle button handling in android for begineers

The toggle button is like a check box or radio button, it has two states: On or Off.
The default behavior of ToggleButton is Off state, it displays a gray bar and the text Off.
When in On state it displays a green bar and has the text On.

# res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout android:id="@+id/LinearLayout01"

 <ToggleButton android:id="@+id/togglebtn"
  android:textOff="Off Stage"
  android:textOn="On Stage"

Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF".

import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;
public class ToggleDemo extends Activity {
    public void onCreate(Bundle icicle) {
        final ToggleButton tbtn = (ToggleButton)this.findViewById(;
        tbtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (tbtn.isChecked()) {
                } else {

This captures the ToggleButton element from the layout, then adds an View.OnClickListener. TheView.OnClickListener must implement the onClick(View) callback method, which defines the action to perform when the button is clicked. In this example, the callback 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.


Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...


Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0