![]() |
VOOZH | about |
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.
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:
| Attribute | Description |
|---|---|
| android:id | The ID assigned to the toggle button |
| android:textOff | The text is shown on the button when it is not checked |
| android:textOn | The text is shown on the button when it is checked |
| android:disabledAlpha | The alpha (opacity) to apply to the when disabled. |
Follow is the steps mentioned below to check on the application implementing ToggleButton in it.
To create a new project in Android Studio follow these steps:
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**}