Android Simple ToggleButton Example - ANDROID - Helper

Monday, May 02, 2011

Android Simple ToggleButton Example


SIMPLE TOGGLEBUTTON

SOURCE CODE [main.xml] is

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

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
   
<ToggleButton android:id="@+id/togglebutton"
android:layout_width="150px"
android:layout_height="50px"
android:textOn="ON"
android:textOff="OFF" />

</LinearLayout>

SOURCE CODE [ToggleButtonExample.java] is

package com.ToggleButtonExample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class ToggleButtonExample extends Activity
{
ToggleButton tb;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
                                setContentView(R.layout.main);

                                tb = (ToggleButton) findViewById(R.id.togglebutton);
                                tb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Button is "+tb.getText().toString(),
Toast.LENGTH_LONG).show();
                                                }
                                });
                }
}

The OUTPUT will be


https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6u_STOdAqUT2_RbzY6BhRGlT1i34ezNpLND9r8IiHm0RXwA14hzd7UvL_EVRzeTM5LcwQ_HGgSzBLUsFBVDrnLVrskUYgBAuk2Y6DzEqnlGl-5FU6pIm0oTbjW5g9Ov6AwKIiebhPqLk/

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBjgDu3zozte9iGjYmv8h00MG3c6ca-QCbLxW8sIMqz8eo7fPGMC4w4m8J__0_7KwyKNssPXdXpns6R1TeYDTb86aJyTUaVCSiYsorq1Gu5dkYJ3qt0Zdfi-viQo3i677eFzpKdAl3qB4/

9 comments:

  1. Too easy to understand, thnk u...

    ReplyDelete
  2. useless without the if/else condition:

    if(toggleDebug.isChecked()){
    //dosomething if it has been switched on
    }else{
    //dosomethingelse if it has been switched off
    }

    ReplyDelete
  3. Very useful. Suggestion to others who find it useless is to create your own simple examples and share them.

    Thank You.

    ReplyDelete
  4. Hi Jack, thanks for this helpful android toggle button example! I compiled a list of some top resources on this topic. I included your post. Check it out/ feel free to share. http://www.verious.com/board/Giancarlo-Leonio/creating-a-toggle-button-in-android/ Hope this can be useful to other developers too. :)

    ReplyDelete
  5. Hi,I am developing an cinema ticketing app.I am stuck with seat selection step.What can i add ??either toggle button or button??I am stuck with designing part itself..Please share ur ideas...

    ReplyDelete