Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Toggle Button in Android

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this blog, you will learn about the Toggle Button widget, which is commonly used in Android applications. Widgets are the elements of the user interface that helps provide a smooth interface for the users. Toggle buttons play the role of an on/off button in our Android application. Toggle buttons are a subclass of Composite Buttons. Some common examples of Toggle buttons include Wifi hotspot buttons, Bluetooth buttons, etc.

Implementation

In this section, we will create a sample android application that will use toggle buttons. Follow the steps given below to make this sample application.

Creating an Android Studio Project

You need to first create an Android Studio project before actually creating your Android apps. To create a new project, open up Android Studio and press the New Project button, select Empty Activity as the activity type and implementation language as Kotlin. Select a minimum SDK version as per your requirements.

Don't have Android Studio and environment already set up in your machine? No worries, we got you all covered. Refer to the blog Android Studio and Environment Setup on the Coding Ninjas Website to set up things for a smoother development process.

The main activity XML file

The activity_main.xml file is the most important layout of your application which is referenced when we are building the interface of our application. The code for the ToggleButton widget is written in this file. 

Code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".MainActivity"
    android:background="@color/dirty_white"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="387dp"
        android:layout_height="117dp"
        android:layout_above="@+id/toggleButton"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/welcome_text"
        android:textAlignment="center"
        android:textColor="@color/orange"
        android:textSize="25dp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.086" />

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="136dp"
        android:layout_height="67dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@color/navy_blue"
        android:onClick="ToggleFunction"
        android:textColor="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.444" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="271dp"
        android:layout_height="51dp"
        android:layout_above="@+id/toggleButton"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.7" />

</androidx.constraintlayout.widget.ConstraintLayout>

In the above code, note the following points. We have defined two TextView widgets and one ToggleButton widget in this file. The Toggle Button is sandwiched between the two Text Views. We have assigned the ID for the Toggle Button widget as toggleButton, and we have set the onClicked attribute to ToggleFunction. This function is defined in the MainActivity.kt file. Basically, this function describes the action that needs to be performed when the toggle button is clicked. 

The main activity Kotlin file

This is the main file that gets your application running. This file contains the onCreate method, one of the first methods that get called after running our application. The code for MainActivity.kt file is given as below.

Code:

package com.example.togglebutton

import androidx.appcompat.app.AppCompatActivity
import android.widget.ToggleButton
import android.widget.TextView
import android.os.Bundle
import android.view.View
import com.example.togglebutton.R

class MainActivity : AppCompatActivity() {
    var togglebutton: ToggleButton? = null
    var textview: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        togglebutton = findViewById<View>(R.id.toggleButton) as ToggleButton
        textview = findViewById<View>(R.id.textView2) as TextView
    }

    fun ToggleFunction(view: View?) {
        if (!togglebutton!!.isChecked) {
            textview!!.text = "Toggle  Button is OFF"
        } else {
            textview!!.text = "Toggle Button is ON"
        }
    }
}

The ToggleFunction defined in this file references the second TextView defined in the activity_main.xml file. Depending upon the state of the Toggle Button, it sets the text of the TextView with ID textView2.

The Android Manifest XML file

This file is used for registering our activities. We don’t need to change anything in this file and just use the boilerplate code provided by Android Studio for this. The code for the AndroidManifest.xml file is given below.

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.togglebutton">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ToggleButton">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The Resources directory

The resources folder named res in our Android Studio project is an important folder that contains all the resources for our application. It contains all non-coding assets of our application. For example, consider the strings.xml file present under the directory res/values. This file contains the name of the application, which is rendered when we run the application. The code of this file is written below. In this blog, we have named the application as Toggle Button.

Code:

<resources>
    <string name="app_name">Toggle Button</string>
    <string name="welcome_text">Welcome to Toggle Button Tutorial\nBy Coding Ninjas</string>
</resources>

The code for the colors.xml file is given as follows.

Code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="orange">#FF8C00</color>
    <color name="dirty_white">#F0EAD6</color>
    <color name="navy_blue">#02075D</color>
</resources>
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Final Application

When we run the app, the main screen of our application looks as follows.

The following output appears when we press the Toggle Button.

FAQs

  1. How can I change the checked state of the Toggle Button in my application?
    Ans: You can use the void setChecked(boolean checked) method to change the checked state of your Toggle Button.
     
  2. Which XML attribute is used to set the text for the button when the button is not checked?
    Ans: The android:textOff attribute can be used to set the text for the Toggle button when the button is not checked.
     
  3. Why are Toggle Buttons very useful while developing Android apps?
    Ans: Toggle Button helps the users to change the state between ON and OFF. Thus, they become crucial for the developers when they want to detect the change in the state of some property.

Key Takeaways

In this article, we have extensively discussed Toggle Buttons in Android along with a sample application containing the implementation of sample toggle buttons. You can also read the blog Radio Button in Android on the Coding Ninjas Website to create Radio Buttons in your Android application.

We hope this blog has helped you enhance your knowledge regarding Toggle Buttons. If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Implementation
2.1.
Creating an Android Studio Project
2.2.
The main activity XML file
2.3.
The main activity Kotlin file
2.4.
The Android Manifest XML file
2.5.
The Resources directory
3.
Final Application
4.
FAQs
5.
Key Takeaways