开发者

Programmatically set an image based on theme in Android

开发者 https://www.devze.com 2023-03-26 08:45 出处:网络
I want to set an ImageView\'s image source开发者_如何转开发 based on current theme. I have two themes defined, and each has an icon for the ImageView.

I want to set an ImageView's image source开发者_如何转开发 based on current theme. I have two themes defined, and each has an icon for the ImageView.

I have the following in themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Android">
        <item name="tabIconContacts">@style/tabContacts_Android</item>
    </style>
    <style name="Theme.Earthy">
        <item name="tabIconContacts">@style/tabContacts_Earthy</item>
    </style>
</resources>

in attr.xml:

<attr name="tabIconContacts" format="reference" />

and the following in styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="tabContacts_Earthy">
        <item name="android:src">@drawable/theme1_tab_contacts</item>
    </style>
    <style name="tabContacts_Android">
        <item name="android:src">@drawable/theme2_tab_contacts</item>
    </style>
</resources>

and I apply it with setTheme() at the top of onCreate(). Setting the background image on resources defined in XML works fine. I'm struggling to find a nice way of setting the image in the following code:

LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View tabIndicator = li.inflate(R.layout.tab_indicator, mTabHost.getTabWidget(), false);
ImageView iconView = (ImageView) tabIndicator.findViewById(R.id.icon);
iconView.setImageResource( R.style.tabIconContacts ));

Is it possible to swap out drawable resources in this way? I found a lot of articles which mention obtainStyledAttributes, but they don't seem to apply to this situation.

I also can't set the image in the XML definition of tab_indicator because the icon changes with every tab and every theme (around 12 icons in total).

Any help will be greatly appreciated.

0

精彩评论

暂无评论...
验证码 换一张
取 消