Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different icons with different Android SDK versions

I have icons for my Android menu. On Android 3+ I'm using a black ActionBar so the icons are white. However, on Android 2.x the menu is inherently white which means the icons are nearly invisible. How can I use different menu icons for different versions? I'm assuming I can do it using different drawable directories like res/drawable-mdpi-v11, but I'm wondering if there is another way so I don't have to create a bunch of different directories as I add versions or pixel densities.

EDIT: I put dark versions in res/drawable-mdpi and res/drawable-hdpi for use with Android 2.x and I put light versions in res/drawable-mdpi-v11 and res/drawable-hdpi-v11 for use with Android 3.x and higher, but my Android 2.1 (sdk 7) emulator is still showing the light version.

Any idea why?

like image 796
Kenny Wyland Avatar asked Mar 06 '12 20:03

Kenny Wyland


1 Answers

You can Select a theme based on platform version, as outlined in the Styles and Themes dev guide. Define a style in your res/values/styles.xml like this:

<style name="ThemeSelector" parent="android:Theme.Light">
    ...
</style>

Then in a res/values-v11/ folder, select your theme (probably Holo, if you're dark)

<style name="ThemeSelector" parent="android:Theme.Holo">
    ...
</style>

Then add icons to that style. For instance, here's a snippet from the styles.xml file from the HoneycombGallery sample application.

<style name="AppTheme.Dark" parent="@android:style/Theme.Holo">
    ...
    <item name="menuIconCamera">@drawable/ic_menu_camera_holo_dark</item>
    <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_dark</item>
    <item name="menuIconShare">@drawable/ic_menu_share_holo_dark</item>
</style>

The bottom 3 elements are all icons in the drawable directories. You'll still need at least one folder per resolution-specific set of icons, but you can combine the light & dark icons into the same folder, but you won't have to have different folders of icons for each platform version. Also, you'll need to list them as references in the values/attrs.xml file, like this:

<resources>
  <declare-styleable name="AppTheme">
    <attr name="listDragShadowBackground" format="reference" />
    <attr name="menuIconCamera" format="reference" />
    <attr name="menuIconToggle" format="reference" />
    <attr name="menuIconShare" format="reference" />
  </declare-styleable>
</resources>

At which point you'll be able to refer to them within your layout XML using the "?attr/NameOfYourDrawable" dereference, like this:

<item android:id="@+id/menu_camera"
      android:title="@string/camera"
      android:icon="?attr/menuIconCamera"
      android:showAsAction="ifRoom" />
like image 195
Alexander Lucas Avatar answered Oct 19 '22 23:10

Alexander Lucas