Saturday, September 8, 2012

Create a Toggle Button In Android

This is a sample activity which shows How to create a Toggle Button in android. Last topic published on this forum is Read Contacts from device.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project ToggleButtonDemo.
2.) Put the following code snippet in res/layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:orientation="vertical" android:layout_width="fill_parent"
        <TextView android:id="@+id/tv" 
android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="@string/hello" />
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1"android:layout_width="wrap_content" android:layout_height="wrap_content"android:textOn="yello" android:textOff="red">
3.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. ToggleButtonDemo. Enter following information:
Project name: ToggleButtonDemo
Build Target: Android APIs2.1
Application name: ToggleButtonDemo
Package name:
Create Activity: ToggleButtonDemo
On Clicking Finish ToggleButtonDemo code structure is generated with the necessary Android Packages being imported along with ToggleButtonDemo class will look like following:
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class ToggleButtonDemo extends Activity implements OnClickListener
    ToggleButton tg;
    TextView tv;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        tv = (TextView) findViewById(;
        tg = (ToggleButton) findViewById(;
    public void onClick(View v) {
        // TODO Auto-generated method stub
Output –The final output:

No comments:

Post a Comment