VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/togglebutton-in-kotlin/

⇱ ToggleButton in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ToggleButton in Kotlin

Last Updated : 15 Jul, 2025

In Android, the ToggleButton is just like a switch containing two states either ON or OFF which are represented using boolean values true and false respectively. ToggleButton unlike switch does not have a slider interface i.e. we cannot slide to change the states. It is just like a button. In this article, we will be discussing how to create a ToggleButton in Kotlin.

Android ToggleButton XML Attributes

Note: ToggleButton inherits the button class of android. Therefore, all the attributes of the button are also applicable here.

Following are some of the additional important attributes available along ToggleButton:

AttributeDescription
android:idThe ID assigned to the toggle button
android:textOffThe text is shown on the button when it is not checked
android:textOnThe text is shown on the button when it is checked
android:disabledAlphaThe alpha (opacity) to apply to the when disabled.

Steps to Demonstrate Implementation ToggleButton

Follow is the steps mentioned below to check on the application implementing ToggleButton in it.

Step 1: Create a new project in Android Studio

To create a new project in Android Studio follow these steps:

  • Click on File, then New, and then New Project, and give a name whatever you like.
  • Choose “Empty Activity” for the project template.
  • Then, select Kotlin language Support and click the next button.
  • Select minimum SDK(According to the application need).

activity_main.xml:

Step 2: Accessing the Toggle Button

The toggle button in the layout can be accessed using the findViewById() function.

val toggle: ToggleButton = findViewById(R.id.toggleButton)

After accessing set a listener to perform actions based on the toggle state using setOnCheckedChangeListener() method.

toggle.setOnCheckedChangeListener { _, isChecked -> **Perform Any Action Here**}

MainActivity.kt:

Run on Emulator:


Comment
Article Tags:

Explore