Android Switch and ToggleButton

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. :)

Download Source Code – >

 

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)
Email (required)