41

For the application I am currently developing, I need to adapt the layout of the different activities to the user's Android API level.

Is there a way to do this?

JDJ
  • 4,298
  • 3
  • 25
  • 44
Atheh
  • 615
  • 1
  • 6
  • 11

3 Answers3

87

If what you're trying to do is show a different layout depending on which API version is available on the device, you want to use configuration qualifiers. The specifics for alternative resources are also documented.

The most basic way to do it is to create a layout folder for each API level you want to use, formatted as follows:

res/layout/mylayout.xml       (Default)
res/layout-v4/mylayout.xml    (Android 1.6)
res/layout-v11/mylayout.xml   (Android 3.0)

and so on, where vN is the API level. The specific API levels can be found on this page.

Jess
  • 42,368
  • 6
  • 37
  • 51
  • If I only had the three files described above, but I use a GB Device, which file will it use? (layout-v4 or layout)? Do I have to create a different folder for every platform? I plan to support from GB onwards – Frederic Yesid Peña Sánchez Apr 04 '13 at 22:21
  • 8
    @FredericYesidPeñaSánchez It will fall backwards to the next most-matching layout. So res/layout will always be matched last, making it required, but any other is optional. You don't need a folder for every platform unless you need something to be different on each. – Jess Apr 05 '13 at 02:09
  • 1
    The links are now dead. The second one is probably this: https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources – Nulano Dec 07 '16 at 14:27
6

As Andrew Koester said you can use the different version folders, but I found this to be a lot of work because it would not fall back to the default layout. If you used layout-v14, it will work,but any api after 14 will also have this layout and you must use another layout-v? to override it again. It all depends on what your doing, but I found if your doing a lot of stuff programmatically this works wonders:

if(Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
            //ex. if ics is met then do this

        }else{
            //if api is not ics then do this
        }
jeff darnell
  • 65
  • 1
  • 3
0

If you already have drawable resources for each of the platform level, you can use the information provided in http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources

More specifically, look at the 'Platform Version (API Level)' row in Table 2.

Vino
  • 1,544
  • 1
  • 18
  • 26