Android Switch button example

Android Switch Button is UI widget which has only two states i.e. ON and OFF. It allows user to change setting between these two states.

Android Switch button is available only in Android 4.0 or later android devices.

Example :
You can use these buttons to change On and Off state of WiFi or Bluetooth

Source code:

Step 1 :Creating Project

Create an android application project named “SwitchButtonExampleApp”.

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 Switch reference from layout file and then using Switch setOnClickListener to register event for state change.
Switch’s isChecked() method is used to know current state of Switch 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 switch button, it will go to on state.

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

Was this post helpful?

Leave a Reply

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