Android Switch and ToggleButton - Androhub

Switch and Toggle Button

Android Switch and ToggleButton

Switch

A switch is type of button that can only have two states ON and OFF. You can set the initial state and then the user can change it. To get the current state you can check if the switch is checked or not, in addition to that you can attach a OnCheckedChangeListener to the switch to get notification when the state changes.

ToggleButton

Toggle button looks like a button but works like a switch. You can choose to implement the same functionality using just 2 radio buttons or a single checkbox. Just like a checkbox a Toggle button has two states whether or not its checked. You can customize the Text for both states, defaults are ON/OFF.

Example

In this example I will show you how to implement both Switch and ToggleButton.

VIDEO DEMO

Let’s get start by creating a project in Eclipse IDE.

1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)

2. Open your your AndroidManifest.xml file and set minSdkVersion to 14, because Switch only works from 14 API Level.

3.  Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml. In this layout i had just taken one switch and one togglebutton.

4. Now, come to MainActivity.java and add the following code. In this class a Toast will be displayed when switch or togglebutton checked change.

5. Now, run the app and you will get the output as shown in video.

Thanks. :)

 

1 Comment

Tia
Monday, May 21st, 2018

Thanks a lot for this tutorial! It helped me

Post comment

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