Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.

It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider control.

Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class

ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class

The 3 XML attributes of ToggleButton class.

XML Attribute Description
android:disabledAlpha The alpha to apply to the indicator when disabled.
android:textOff The text for the button when it is not checked.
android:textOn The text for the button when it is checked.

Methods of ToggleButton class

The widely used methods of ToggleButton class are given below.

Method Description
CharSequence getTextOff() Returns the text when button is not in the checked state.
CharSequence getTextOn() Returns the text for when button is in the checked state.
void setChecked(boolean checked) Changes the checked state of this button.

Android ToggleButton Example


Drag two toggle button and one button for the layout. Now the activity_main.xml file will look like this:

File: activity_main.xml
<?xml version=“1.0” encoding=“utf-8”?>
< xmlns:android=“”
        app:layout_constraintTop_toTopOf=“parent” />
        app:layout_constraintTop_toTopOf=“parent” />
        app:layout_constraintStart_toStartOf=“parent” />

Activity class

Let’s write the code to check which toggle button is ON/OFF.

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
    private ToggleButton toggleButton1, toggleButton2;
    private Button buttonSubmit;
    protected void onCreate(Bundle savedInstanceState) {
    public void addListenerOnButtonClick(){
        //Getting the ToggleButton and Button instance from the layout xml file
        //Performing action on button click
        buttonSubmit.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view) {
                StringBuilder result = new StringBuilder();
                result.append(“ToggleButton1 : “).append(toggleButton1.getText());
                result.append(“\nToggleButton2 : “).append(toggleButton2.getText());
                //Displaying the message in toast
                Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();


android toggle button example output 1 android toggle button example output 1