android – Backwards compatible Switch-ThrowExceptions

Exception or error:

ICS has a Switch component. It does what we need. Is there anything out there backward compatible to (about) 2.2? Couldn’t find anything obvious.

Looks like somebody built this:

How to solve:

Switch is only on 4.0+

If you want to make an app that uses switch on 4.0+ devices what you need to do is declare two layouts. The first in layout-v14 which will be what’s used on ICS devices. In your layout folder make use of CheckBox.

In your code make use of the CompoundButton class when getting/setting data from the switch or checkbox. You’ll find that CompoundButton works well for this.


Android support AppCompat library from version 21.0.0 contains to provide compability back to API v7.

Include it like this with gradle:

compile ''

It can be used in layouts like this:

< />

In addition it has showText attribute to make styling easier – which seems to be missing from native andriod Switch.


you should use checkbox when such a thing is impossible , as described here:

(slide 32)


This library is what you’re looking for :


Here is an example of SwitchCompat

First thing to do make sure you add this lines to your build.gradle and then sync.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

Second create a sample Activity , in my case I will call it

public class SwitchActivity extends ActionBarActivity {

        SwitchCompat mySwitch = null;

        protected void onCreate(Bundle savedInstanceState) {

            // here is your switch
            mySwitch = (SwitchCompat)findViewById(;


Lastly create your Layout , in my case I will call it activity_switch.xml.

<RelativeLayout xmlns:android=""

        android:layout_width="wrap_content" />



If you are using the holoeverywhere library, you can use something like this in your layout file


Leave a Reply

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