Android Projects

Android Development Books

Tuesday

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"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:gravity="center">

 <ToggleButton android:id="@+id/togglebtn"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textOff="Off Stage"
  android:textOn="On Stage"
  android:background="@drawable/icon"/>
  </LinearLayout>



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


package com.horror.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;
public class ToggleDemo extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icircle);
        setContentView(R.layout.main);
     
        final ToggleButton tbtn = (ToggleButton)this.findViewById(R.id.togglebtn);
     
        tbtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (tbtn.isChecked()) {
                 tbtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.andioon));
                } else {
                 tbtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.andiooff));
                }
             }
        });
    }
}




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.

References:


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...

0 comments

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