如何从drawable引用到样式

9
我的带有选项卡的应用程序有两个主题。在每个主题中,选项卡在选定和未选定状态下具有不同的图像。我该如何正确地引用主题图片?
例如,我在themes.xml中有以下内容:
<?xml version="1.0" encoding="utf-8"?>

<style name="LightTheme" parent="@android:style/Theme.Light">
    <item name="tabShows">@drawable/ic_tab_shows_unselected_light</item>
    <item name="tabShowsSelected">@drawable/ic_tab_shows_selected_light</item>
    <item name="tabNews">@drawable/ic_tab_news_selected_light</item>
    <item name="tabNewsSelected">@drawable/ic_tab_news_unselected_light</item>
</style>

<style name="DarkTheme" parent="@android:style/Theme.Black">
    <item name="tabShows">@drawable/ic_tab_shows_unselected_dark</item>
    <item name="tabShowsSelected">@drawable/ic_tab_shows_selected_dark</item>
    <item name="tabNews">@drawable/ic_tab_news_selected_dark</item>
    <item name="tabNewsSelected">@drawable/ic_tab_news_unselected_dark</item>
   </style>

我有一个tab_shows.xml和tab_news.xml。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item  android:state_selected="true" android:drawable="@drawable/ic_tab_shows_selected_light"/>
<item  android:state_selected="false" android:drawable="@drawable/ic_tab_shows_unselected_light" />

我如何根据当前主题在选择器中引用所需的图像? 这对我无效。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item  android:state_selected="true" android:drawable="?tabShowsSelected"/>
<item  android:state_selected="false" android:drawable="?tabShows" />

在布局文件中,通过使用“?styleName”引用样式是有效的。
2个回答

5

构建您的样式A和样式B

在您的情况下,您需要将 android:drawable="@drawable/ic_tab_shows_selected_light" 放置在背景而不是替换背景(我只是从我的代码中复制了一些片段)

#000

    <style name="styleB">
        <item name="android:background">#000</item>
    </style>

您的主题A

<style name="Theme.A">
        <item name="pageBackground">@style/styleA</item>
    </style>

主题B

<style name="Theme.Blue">
        <item name="pageBackground">@style/styleB</item>
    </style>

在您的attr.xml文件中。
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="pageBackground" format="reference" />
</resources>

在你的小部件中,最终你需要使用style="?pageBackground"

3
你可以在这里找到答案:http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html 编辑 (Lukap在评论中提供的额外信息)
  1. themes.xml中定义一个或多个主题,并在那里设置你的样式定义。
  2. attrs.xml中定义自定义属性,也称为自定义样式。
  3. styles.xml中描述你自定义样式的值。
但是,你需要阅读有关attrs.xml的更多信息。
<item name="android:background">? android:attr/activatedBackgroundIndicator</item> 
</style> 

相反,我们从继承的主题中引用了另一个属性activatedBackgroundIndicator的值。不管主题定义activatedBackgroundIndicator为何,都将成为我们的背景。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接