![]() |
VOOZH | about |
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.
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.
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. |
In this step, open the XML file and add the code to display the toggle button and a textview.
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 |
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.
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