Friday, August 29, 2014

Switching an Android Menu Icon via Themes

First, edit attrs.xml to include the name:  <attr name="undo_icon"

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="undo_icon" format="reference" />
</resources>

Then, edit the styles.xml to define the style: <item name="undo_icon">

<resources>
    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->     
    </style>

    <!-- Application theme. -->
    <style name="AppThemeLight" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
        <item name="undo_icon">@drawable/halo_dark_content_undo</item>       
    </style>
    <style name="AppThemeDark" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
        <item name="undo_icon">@drawable/halo_light_content_undo</item>
    </style>
</resources>

Finally, define the menu.xml: android:icon="?undo_icon"

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/menu_undo"
        android:icon="?undo_icon"
        android:title="Undo"
        android:titleCondensed="Undo">
    </item>
</menu>

In the Manifest: android:theme="@style/AppThemeLight" >  OR switch dynamically via Context.setTheme

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppThemeLight" >


To reference in code:

        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.
undo_icon, typedValue, true);
        btnUndo.setImageResource(typedValue.resourceId);


No comments:

Post a Comment