Tutorial

Android Toggle Button, Switch Example

Published on August 4, 2022
author

Anupam Chugh

Android Toggle Button, Switch Example

Today we will learn about Android Toggle Button and Switch in android app. We’ll discuss and implement Switch button Widget and the ToggleButton widget in our application.

Android Toggle Button

Android Toggle Button is used to display on and off state on a button. Switch is another type of toggle button that’s predominantly used since Android 4.0. Android Switch provides a slider control. Both ToggleButton and Switch are subclasses of CompoundButton class. XML Attributes used to define a ToggleButton are described below.

  1. android:disabledAlpha: The alpha to apply to the indicator when disabled
  2. android:textOff: The text for the button when it is not checked
  3. android:textOn: The text for the button when it is checked

To modify the ToggleButton programmatically the following methods are used.

  1. CharSequence getTextOff(): It returns the text when button is not in the checked state
  2. CharSequence getTextOn(): It returns the text for when button is in the checked state
  3. void setChecked(boolean checked): It changes the checked state of this button

Android Switch

Android Switch or SwitchCompat widget ( a part of AppCompat library which provides backward compatibility for lower Android versions upto Android API v7) is a custom On-Off slider which is commonly seen in phone settings. Advantages of Android Switch Widget:

  1. It is the best replacement for checkboxes and RadioButtons
  2. Implementation takes only less than a minute
  3. No need to use much drawables and other resources

The xml layout of a SwitchCompat is given below:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />

android:text is used to display a Text besides the slider switch button.

Android Toggle Button and Switch Example

In this application we’ll display two ToggleButton and one Switch button. The state of the Toggle Buttons would be displayed in a SnackBar when the FloatingActionButton is pressed. The state of the Switch button is changed to true whenever the action button of the snackbar is clicked. Or the state is displayed in the snackbar by sliding the switch.

Android Toggle Button and Switch Project Structure

android toggle button, switch in android

Android Toggle Button Code

The activity_main.xml remains the same. The content_main.xml contains two Toggle Buttons and a Switch checked to false by default as shown in the code snippet below :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.switchandtoggle.MainActivity"
    tools:showIn="@layout/activity_main">

    <ToggleButton
        android:id="@+id/tb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="ToggleButton 1"
        android:textOff="Off"
        android:textOn="On" />

    <ToggleButton
        android:id="@+id/tb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tb1"
        android:layout_alignBottom="@+id/tb1"
        android:layout_toRightOf="@+id/tb1"
        android:text="ToggleButton 2"
        android:textOff="Off"
        android:textOn="On" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:checked="false"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />


</RelativeLayout>

The MainActivity.java is given below:

package com.journaldev.switchandtoggle;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    ToggleButton tb1, tb2;
    SwitchCompat switchCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                StringBuilder result = new StringBuilder();
                result.append("ToggleButton1 : ").append(tb1.getText());
                result.append("\nToggleButton2 : ").append(tb2.getText());

               Snackbar snackbar= Snackbar.make(view, result.toString(), Snackbar.LENGTH_LONG)
                        .setAction("SWITCH ENABLE", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switchCompat.setChecked(true);
                            }
                        });

                snackbar.setActionTextColor(Color.RED);
                snackbar.show();
            }
        });

        tb1= (ToggleButton)findViewById(R.id.tb1);
        tb2=(ToggleButton)findViewById(R.id.tb2);
        switchCompat=(SwitchCompat)findViewById(R.id.switchButton);

        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                Snackbar.make(buttonView, "Switch state checked "+isChecked, Snackbar.LENGTH_LONG)
                        .setAction("ACTION",null).show();
            }
        });



    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A String builder is used to get the current state of the toggle buttons and append them to display in the snackbar. Switch button being a subclass of Compound Button, an OnCheckChangeListener is implemented as shown in the code above. The output below is the app in action. android toggle button example, switch in android This brings an end to android toggle button and switch in android tutorial. You can download the final Android SwitchAndToggle Project from the link below.

Download Android Switch and Toggle Button Project

Reference: ToggleButton Android Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 29, 2021

Hey, i want to play music everytime when switch is checked and stop when it is unchecked. But this action performs only 1 time. What to repeat action when everytime switch is clicked. s1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (s1.isChecked()) { mp1.start(); } else { mp1.stop(); } return; } }); Thankyou in advance!

- Shubhangi

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 1, 2018

    Hi, I am working on android application. I want to make a incoming call user interface . Like usually incoming call user interface having a single button. When user get a call from another mobile device. The incoming call user interface showing a single button moving up and down. Then user has to press button and move to up. i.e call answering. Second one user has to press button and move to down.i.e call decline. Like that only i want to design. Any idea for that. Please any having a idea about it.Please help me. Thanks in Advance, Amar.

    - Amar Pulli

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 25, 2018

      Thank You. :-)

      - SURAJ RAJBHAR

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 23, 2018

        Thank you! This isn’t so well documented online.

        - NOONEUNDERSTAANDS

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.