Search code examples
androidandroid-layoutandroid-xmlandroid-custom-view

Better way to use various versions of custom View in XML layout in different API levels?


For example I have two versions of my custom View called MyView (for API 4-10) and MyView_v11 (for API 11+). They both inherit from the View class in Android. MyView_v11 simply extends MyView and overrides one method of View which is only available in API 11+.

Currently I'm using different layout files like:

layout
    main_activity.xml
layout-v11
    main_activity.xml

The first layout defines a view which points to MyView, the second one only changes that view and points it to MyView_v11.

My question: How can I use only one file like layout/main_activity.xml with some separate helper layout files for different API levels? Because in the layout there are lots of other views, but only one custom view. I want to use the same technique as the one that Andoid SDK uses to generate R.style.AppTheme when you create new sample Android project:

values:
    <style name="AppTheme" parent="@android:style/Theme" />
values-v11:
    <style name="AppTheme" parent="@android:style/Theme.Holo" />

Edited: I'd prefer other solutions over commonsware. I hope this is right.


Solution

  • You could always put MyView in its own separate layout, and use include to reference it in your main_activity.xml. Then you would just need two API specific versions of your simple my_view_layout.xml layout and only one main_activity.xml. This would allow you to copy as little xml as possible.

     layout
         main_activity.xml
         my_view_layout.xml
     layout-v11
         my_view_layout.xml
    

    http://developer.android.com/training/improving-layouts/reusing-layouts.html