Posted by & filed under Android, Java, Tipps & Tricks.

Important notice: I have a newer version available right here

I was coding for my new app and wanted it to be available for a large user base, so Android API Level 10 (Gingerbread) had to be the minimum SDK version. I also wanted to have a Switch button introduced in API Level 14 with Ice Cream Sandwich.

An image of switches introduced in Ice Cream Sandwich. This image is from Jelly Bean. An image of switches from Jelly Bean.

I really like the design of the ICS-Switch-button, but it bothers me, that you do not see the other, currently not selected, text. In my head you would always see both texts and the blue rectangle would highlight the text that is currently selected.

So I took the images and the code of the ICS-Switch button and began coding my own version. Here is the result:

Switch Button Demo

Screenshot of the new Switch Button

Find the code and some explanations after the break:

You can get the code here: https://bitbucket.org/ankri/switchbutton/src

Or download the project here: https://bitbucket.org/ankri/switchbutton/downloads/SwitchButtonSampleProject.zip

I couldn’t get the code from Ice Cream Sandwich version of the Switch to run on Gingerbread due to some functions only available in Api Level 11+ and the missing feature of showing text of the unchecked side, so I had to rewrite some of the code. I tried my best to document the code. Please feel free to ask if you do not understand some of it, or feel free to leave feedback.

 

Here is the attrs.xml to style the Switch via xml:

And here the styles.xml to set the colors depending on the theme:

Note: colorChecked is the text color for the checked side of the switch and colorUnChecked is the text color for the unchecked side of the switch.

License

Have fun using the code. I uploaded the code under the Beerware License. You can take the code and do whatever you want with it, as long as you mention me somewhere in your code, or your final app. If we ever meet and you think that the code, or explanation was helpful, feel free to buy me a beer and have a chat.

Or you could help a fellow out by donating some money.

One Response to “Switch Button for Android 2.3 Gingerbread”

  1. Paul

    Hi. This is very usefull, but I have one question: how I can make the swithc disabled. setEnabled(false) doesn’t work. Thanks

Trackbacks/Pingbacks

  1.  Switch backported for Android Api level 8+ Froyo, Gingerbread & co - ankri.de