Thursday, December 13, 2012

Android beginner tutorial: Part 19 - ToggleButton widget

Today we'll see how to use the ToggleButton widget.

A ToggleButton widget is similar to a CheckBox. It acts like a switch - it can be turned on or off. The only thing different from a CheckBox is the appearance. Instead with a box that can be checked, it's a regular button with a label, plus a little LED indicator under the text that changes color when the button is toggled.

The ToggleButton widget has default text values - ON and OFF. They can be set to custom values using android:textOn and android:textOff properties or setTextOn() and setTextOff() methods.

In the example below, I create a simple Activity layout in activity_main.xml that contains a ToggleButton and a text underneath. Set the ids as shown below:

<LinearLayout xmlns:android=""
    tools:context=".MainActivity" >

We'll need to go to strings.xml and define 2 values toggle_on and toggle_off, which will be displayed in the text field when the toggle button changes its state.

<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">Code For Food Test</string>
    <string name="toggle_on">The switch is On</string>
    <string name="toggle_off">The switch is Off</string>
    <string name="menu_settings">Settings</string>


Now go to class. We're going to update the code from the previous tutorial to match our new needs.

We're going to keep the OnCheckedChangeListener class implementation, the onCheckedChanged() function and most of the other code. We're going to declare a ToggleButton "toggle" instead of a CheckBox "check", though. We're also declaring a new TextView "message", which refers to the "message" object in the layout.

Here's the code:

package com.kircode.codeforfood_test;

import android.os.Bundle;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements OnCheckedChangeListener{

public ToggleButton toggle;
public TextView message;

protected void onCreate(Bundle savedInstanceState) {

toggle = (ToggleButton)findViewById(;

message = (TextView)findViewById(;

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;


As you can see, the code is not too different from the previous tutorial, where we handle CheckBox events.

That will be all for today.

Thanks for reading!

No comments:

Post a Comment