Android ToggleButton example

Android ToggleButton is UI widget which has only two states i.e. ON and OFF. It allows user to change setting between these two states.
Example :
You can use these button to change On and Off state of WiFi or Bluetooth

Source code:

Step 1 :Creating Project

Create an android application project named “ToggleButtonExampleApp”.

Step 2 : Creating Layout

Change res ->layout -> activity_main.xml as below:

Step 3 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
We are getting toggle  reference from layout file and then using ToggleButton’s setOnClickListener to register event for state change.
ToggleButton’s isChecked() method is used to know current state of ToggleButton whether it is on state or off state.

Step 4 : Running the app

When you run the app, you will get below screen:

When you click on toggle button, it will go to on state.

When you again click on toggle button, it will go to off state.

We are done with Android ToggleButton example. Please comment if you are facing any issue with the code.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *