![]() |
VOOZH | about |
A Switch or a Switch Button in Android is a UI element that is used to switch between two states upon click. It can be assumed as a Boolean button with two different values. Some states where you may find a Switch in your Android device can be WIFI ON and OFF, Bluetooth ON and OFF, Dark Mode and Light Mode, etc.
In this article, we will show you how you could implement a Switch Button and check its Checked State in Android using Jetpack Compose. Follow the below steps once the IDE is ready.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version.
We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt:
When you run the application you will see that the Switch is initially false. When you click the Button, it will display a Toast with 'false' written. Now, when you click on Switch, it becomes true and if the Button is clicked, it will display a Toast with 'true' written. You can see this happening in the below video of this application.