Setting Android Background & Persistence Menu Bar - Using attribute on older versions causes crash - Is there a theme /pattern approach?

AndroidAndroid Support-Library

Android Problem Overview


In Android 3.0, the concept of "checked" can be rendered using an "activated" background. This gives you the persistent bar you see when you tap on a list fragment, providing context for the fragment to the list's right (e.g., tapping on a folder in Gmail highlights that folder and opens up another list fragment to show the conversations in that folder).

For example, the fragment samples show stuff like:

setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

That resource (android.R.layout.simple_list_item_activated_1) is new to Android 3.0. What makes it "activated" is:

android:background="?android:attr/activatedBackgroundIndicator"

That attribute value is new to Android 3.0 and will cause you to crash if you try using it on earlier versions of Android, from what I can tell. I want to set the background to this magic value for the 3.0/large/landscape combination, and skip it otherwise.

I can accomplish this by having two separate versions of the layout, one in a -v11 resource set, one in a regular resource set. This is a bit less DRY than I'd like, though, since the bulk of the layout is the same, with only this one attribute either being included or being skipped.

I took a stab at trying to use drawable resource aliases, so the android:background could refer to the alias and the alias would handle the -v11 differentiation, but <bitmap> drawables don't seem to like android:src="@null".

I suspect there's a styles-and-themes approach to this problem, but since I've never fully wrapped my head around those (one of my more embarrassing Android knowledge gaps), I'm not completely sure what to do.

Has anyone worked out a pattern for using "activated" on 3.0 and skipping it on pre-3.0, beyond separate layouts?

Thanks!

Android Solutions


Solution 1 - Android

Styles are your friend....

Have two values directories, one is values-v11, the other the default values.

Each values directory contains a styles.xml, the difference being that the default values one contains;

<style name="listViewActivatedStyle"/>

The values-v11 contains;

<style name="listViewActivatedStyle">
   <item name="android:background">?android:attr/activatedBackgroundIndicator</item>
</style>

Then you can have a single layout which uses;

style="@style/listViewActivatedStyle"

and the appropriate one is selected.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCommonsWareView Question on Stackoverflow
Solution 1 - AndroidAl SuttonView Answer on Stackoverflow