How to add Toggle Button in an Android Application

ToggleButton is basically a stop/play or on/off button with an indicator light indicating the current state of ToggleButton. ToggleButton is widely used, some examples are on/off audio, Bluetooth, WiFi, hot-spot etc. This is a subclass of Composite Button.


ToggleButton allows users to change settings between two states from their phone’s Settings menu such as turning their WiFi, Bluetooth, etc. on / off. Since the Android 4.0 version (API level 14), it has another type of toggle button called a switch which provides user slider control.

Note: Programmatically, the isChecked() method is used to check the current state of the toggle button. This method returns a boolean value. If a toggle button is ON, this returns true otherwise it returns false. Below is an example in which the toggle button is used.

Steps by Step Implementation of Toggle Button

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note: Select Java as the programming language.

Step 2: Creating a layout to display the ToggleButton

Important Operations can be performed using XML Attributes:

Operation

XML Attribute

android:textOn

Used to change the text to be displayed when the button is On. By default text is “ON”

android:textOff

Used to change the text to be displayed when the button is Off. By default text is “OFF”

android:disabledAlpha

The alpha to apply to the indicator when disabled.

Navigate res>layout>activity_main.xml:ges the state of the button



In this step, open the XML file and add the code to display the toggle button and a textview.

acticity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="20dp"
        android:textSize="24sp" />

    <ToggleButton
        android:id="@+id/button_toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="onToggleClick" />


</LinearLayout>


Step 3: Using Methods Associated with the ToggleButton

We will update the methods to test the full ability of out Togglebutton.

Method

Description

CharSquence getTextOn()

Returns the text when button is On

CharSquence getTextOff()

Returns the text when button is Off

void setChecked(boolean checked)

Changes the state of the button

Navigate Open the app -> Java -> Package -> Mainactivity.java


In this step, open MainActivity and add the below code to initialize the toggle button and add onToggleClick method which will be invoked when the user clicks on the toggle button. This method changes the text in textview.

MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    ToggleButton togglebutton;
    TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize the toggle button and text view
        togglebutton = (ToggleButton) findViewById(R.id.toggleButton);
        textview = (TextView) findViewById(R.id.textView);
    }

    // Method is called when the toggle button is clicked
    public void onToggleClick(View view) {
        if (togglebutton.isChecked()) {
            textview.setText("Toggle is ON");
        } else {
            textview.setText("Toggle is OFF");
        }
    }
}
MainActivity.kt
package com.gfg.toggle_button

import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.ToggleButton
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    lateinit var toggleButton: ToggleButton
    lateinit var textView: TextView
      
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialize the toggle button and text view
        toggleButton = findViewById(R.id.button_toggle)
        textView = findViewById(R.id.textView1)

    }

    // Method is called when the toggle button is clicked
    fun onToggleClick(view: View) {
        if (toggleButton.isChecked) {
            textView.text = "Toggle is ON"
        } else {
            textView.text = "Toggle is OFF"
        }
    }
}


Output:

Now connect your device with USB cable and launch the application. You will see a toggle button. Click on the toggle button which will display the status of the toggle button.


The Final Application Created Can be downloaded from this link – GitHub Link for the Toggle Key in Android Application




Contact Us