Create A Toggle Button

 

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"?-->
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

 

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: com.app.ToggleButtonDemo
Create Activity: ToggleButtonDemo

On Clicking Finish ToggleButtonDemo code structure is generated with the necessary Android Packages being imported along with ToggleButtonDemo.java. ToggleButtonDemo class will look like following:

 

package com.app.ToggleButtonDemo;

import android.app.Activity;
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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
tv.setBackgroundColor(0xfff00000);
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((tg.isChecked()))
{
System.out.println("checked");
tv.setBackgroundColor(0xffffff00);
}
else
{
System.out.println("Unchecked");
tv.setBackgroundColor(0xfff00000);
}
}
}

 

 

Output –The final output:

Leave a Comment:

3 comments
Sunantha says April 16, 2013

Hi, I am developing a cinema ticketing App.I am stuck with seat selection layout design.. How can i proceed further..???Pl share your ideas..

Reply
consult a professional fitter wedding dress to find out your body type14 says June 7, 2013

Script failed (code “ERROR_NEED_MAJOR_UPGRADE_USE_IMP_EXP”) when installing “CentralMgmtStoreI follow the LS_Deploy_SE.doc instructions, and never create the RTC instance in SQL, there are no policies, permission according to the documentation, and allways repeat the same error. Can you help me. Thanks.

Reply
Mayaa says August 5, 2013

Thanks for your post man, was really good.. This http://www.compiletimeerror.com/2013/08/android-togglebutton-example.html also may help, have a look…

Reply
Add Your Reply