A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a light indicator.
A toggle button allows the user to change a setting between two states.
Android ToggleButton simple usage in xml layout is given below:
Android provides several text decorating attributes like Typeface, font family, text style, text size, text color, text shadow etc. which are applicable on Android ToggleButton too, you can learn it here:
Let's discuss xml attributes of Android ToggleButton
To check an android ToggleButton in xml set android:checked attribute of Android ToggleButton as true. To uncheck an Android ToggleButton in xml set android:checked attribute of Android switch as false.
android:textOff specify the text to use when the ToggleButton is in the unchecked or "off" state.
android:textOn specify the text to use when the ToggleButton is in the checked or "on" state.
In this sample, to customize ToggleButton, I created 2 xml selector under drawable folder, one for color selector and second one to drawableLeft icon on checked and unchecked state of ToggleButton.
I have copied 2 images named toggle_on.jpg & toggle_off.jpg in drawable folder.
Android ToggleButton is a view and we can handle click event of Android ToggleButton like any other Android View.
A simple way to handle click event of Android ToggleButton is to declare onClick attribute of Android ToggleButton and implement that method in your activity class as given below:
isChecked method of ToggleButton can be used to check whether ToggleButton status is checked or not.
OnClick event of Android ToggleButton fires once user click on Android ToggleButton. What if we want to perform some action onCheckedChange event of Android ToggleButton?
Android ToggleButton inherits CompoundButton's attributes, so implement CompoundButton.OnCheckedChangeListener interface and override onCheckedChanged method as follows:
Next step is to set setOnCheckedChangeListener of Android ToggleButton in onCreate method of activity as follows:
In this example I have discussed different aspect of Android ToggleButton.
Step 1: Create a new project in Android Studio and name it Android ToggleButton.
Step 2: Open res -> layout -> activity_main.xml and add following code
Step 3: Open your MainActivity.java and replace its source with source of my MainActivity.java as follows:
Step 5: Open res ->drawable and place 2 images, one for checked state of toggleButton and another for uncheck state of ToggleButton
Step 5: Open res ->drawable and create an xml named togglebutton_selector.xml and replace the code with the below given code.
Step 6: Open res ->values->colors.xml and add color code for green and red as follows:
Step 7: Open res ->drawable and add a new xml file named color_selector.xml, and replace its code with below given code:
Step 8: Clean and run the project to see the result.