Rob Rob - 5 months ago 16
Android Question

Android : Required API to use Switch?

I can't insert a Switch in my project because of the following error :


View requires API level 14 (current min is 8):


But in my project properties, I use Platform 4.1 and API Level 16. So what is wrong?

Answer

There is a nice lecture about this from Google IO 2012 (starting at slide 32)

Here is a detailed example:

Create a separate layout XML file for ICS+ versions by placing it in /res/layout-v14. The resulting file structure will look something like this:

res/layout
- mainlayout.xml
- compound_button.xml
res/layout-v14
- compound_button.xml

Android will then look for resources in the layout-v14 directory when your app is running on v14 or higher.

Place an include in mainlayout.xml that will pull in the pertinent compound_button.xml when the app is run:

<include layout="@layout/compound_button" />

For the pre 4.0 layout we want a checkbox, so create /layout/compound_button.xml as a merge as follows:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >

    <CheckBox
        android:id="@+id/enabled"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable" />

</merge>

And then for the 4.0+ layout we want a switch, so create /layout-v14/compound_button.xml as a merge as follows:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" >

    <Switch
        android:id="@+id/enabled"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable"
        tools:ignore="NewApi" />

</merge>

Of course, be sure to set your min and targets appropriately:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />
Comments