Android Toggle Button example


Toggle button is very useful if you want to switch between two states. A toggle button takes only two states ACTIVATED state & DEACTIVATED state [or] ON state and OFF state. This is the best alternative for radio buttons.

We can easily create Toggle buttons using <ToggleButton> tag in android layout. We can explicitly set the ON/OFF state texts in the xml layout. The default value for on state is ‘ON’ and for off state is ‘OFF’.
Listener for the button click can be created programmatically or can also be declared in the layout xml itself using android:onClick property.
For example:
‘onToggleClicked’ is the method in the Activity class that uses this layout. This method should take one parameter of type ‘View’

To handle the click event programmatically we setOnCheckedChangeListener is used.

In the example given below I have created two toggle buttons
ToggleButton1 is with default on/off text and its click event is declared in the xml file.
ToggleButton2 shows custom on/off text values and its click event is handled programmatically.

Layout xml file:

Activity class:

1 2 3 4

Leave a Reply