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/ 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:

💻 Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️

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.

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.