Android ToggleButton example

In Android, the “android.widget.ToggleButton” is a special class to render a button which has only two states, for example, “on and “off”. It’s best alternative to radio buttons to turn on or turn off a function.

In this tutorial, we show you how to use XML to create two toggle buttons and a normal button, when user click on the normal button, it will display the current state of both toggle buttons.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Custom String

Open “res/values/strings.xml” file, add some custom string for toggle buttons.

File : res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MyAndroidApp</string>
    <string name="toggle_turn_on">Turn On</string>
    <string name="toggle_turn_off">Turn Off</string>
    <string name="btn_display">Display</string>
</resources>

2. ToggleButton

Open “res/layout/main.xml” file, add two “ToggleButton” and a normal button, inside the LinearLayout.

File : res/layout/main.xml


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

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="@string/toggle_turn_on"
        android:textOff="@string/toggle_turn_off"
        android:checked="true" />

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />

</LinearLayout>
Note
Review the “togglebutton2”, we did customized the togglebutton2’s display text on and off and made it checked by default.

3. Code Code

Inside activity “onCreate()” method, attach a click listeners on a normal button, to display the current state of the toggle button.

File : MyAndroidAppActivity.java


package com.mkyong.android;

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

public class MyAndroidAppActivity extends Activity {

  private ToggleButton toggleButton1, toggleButton2;
  private Button btnDisplay;

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

	addListenerOnButton();

  }

  public void addListenerOnButton() {

	toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
	toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
	btnDisplay = (Button) findViewById(R.id.btnDisplay);

	btnDisplay.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {

		   StringBuffer result = new StringBuffer();
		   result.append("toggleButton1 : ").append(toggleButton1.getText());
		   result.append("\ntoggleButton2 : ").append(toggleButton2.getText());

		   Toast.makeText(MyAndroidAppActivity.this, result.toString(),
			Toast.LENGTH_SHORT).show();

		}

	});

  }
}

4. Demo

Run the application.

1. Result, toggleButton2 is using the customized string, and checked by default.

android togglebutton demo1

2. Checked toggleButton1 and unchecked toggleButton2, and click on the display button, the current state of both toggle buttons will be displayed.

android togglebutton demo2

Download Source Code

Download it – Android-ToggleButton-Example.zip (15 KB)

References

  1. Android ToggleButton JavaDoc
  2. Android ToggleButton example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Isaac Darlong
Guest
Isaac Darlong

Why do we need another button to display the state of toggle button this is ridiculous. Why can’t just the state on toggle view being clicked itself.

Michel GilliƩron
Guest
Michel GilliƩron

You can consider the button to display as a summary of states before their saves, by imagining the case you would have several toggle buttons. What would happen if you change the state of some of these buttons and after you decide to cancel your changes ?
If the state was saved when changing the corresponding toggle button, you would have to remember what was its initial state.

Abhijit
Guest
Abhijit

Is it me or everyone else also think that it is confusing ? one button could have done the thing . why complicate it ?

viraj shukla
Guest
viraj shukla

good

LOUWRENS VAN DEVENTER
Guest
LOUWRENS VAN DEVENTER

I have struggled with this lesson for a while, after playing around I discovered that setContentView (R.layout.main); in MyAndroidAppActivity.java was messing up my application. I have blanked this out and now my app is running for the first time. Obviously I do not get anything back if I press the Display button on the app now. Hope this helps someone, please give advice I you want to. Regards Louwrens van Deventer (South Africa)

kewal
Guest
kewal

its confusing and is more confusing when doing on android studio..iam beginner with a little knowledge

Manojkumar
Guest
Manojkumar

please send me Google map source code in android in simple code.

aide
Guest
aide

please my question not about this lesson but i use android for hand gesture recognition and dont have any idea about what i can do please can u help if u know or any body have any idea

trackback
Sending string from andriod to computer through WiFi using single image button : Android Community - For Application Development

[…] Complete tutorial you can get it here: Android toggle button example. […]

trackback
How to change background resource of an image button to implement on/off switch : Android Community - For Application Development

[…] use ToggleButton. numerous examples available like here. […]

Giancarlo Leonio
Guest
Giancarlo Leonio

Thanks for this Android ToggleButton example! I compiled a list of some top resources I found on creating toogle buttons in android. I included you post. Check it out/ free to share. http://www.verious.com/board/Giancarlo-Leonio/creating-a-toggle-button-in-android/ Hope other developers find this useful too. :)

Nayyi
Guest
Nayyi
Toast.makeText(MyAndroidAppActivity.this, result.toString(),
			Toast.LENGTH_SHORT).show();

was not working.why?

Ziad Gholmish
Guest
Ziad Gholmish

you can use this instead of buffer:-

Toast.makeText(getApplicationContext(),toggleButton1 .getText() +”\n” + toggleButton2.getText() , Toast.LENGTH_LONG).show();

Abhishek Agarwalla
Guest
Abhishek Agarwalla

Toast.makeText(MyAndroidAppActivity.this, result.toString(),Toast.LENGTH_SHORT).show();

Instead of this, you can use:
Toast.makeText(this, result.toString(),Toast.LENGTH_SHORT).show();

Abhijeet
Guest
Abhijeet

Buttons are quite ugly!

trackback
Android Tutorial

[…] Android toggle button example Use “ToggleButton” to render a button which has only two states (On and Off). […]

Mike Petersen
Guest
Mike Petersen
public static ToggleButton  gainhitsTBtn; 
gainhitsTBtn  = (ToggleButton) findViewById(R.id.gainhits); 

These statements have no effect on visibility of the ToggleButton view.

Tims.gainhitsTBtn.setVisibility(View.VISIBLE); 
Tims.gainhitsTBtn.setVisibility(View.INVISIBLE); 

why?

Thanks for your input!

mike

arun
Guest
arun
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class ActtoActActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Button button1 ; super.onCreate(savedInstanceState); setContentView(R.layout.main); button1 =(Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click Intent myIntent1 = new Intent(v.getContext() , two.class); startActivity(myIntent1); } }); } }