使资源主题依赖

S.D*_*.D. 29 android android-theme

现在我们有两个图标(暗和亮),如ActionBar图标指南中所述.

@drawable/ic_search_light 
@drawable/ic_search_dark
Run Code Online (Sandbox Code Playgroud)

如何在XML菜单资源中引用这些图标:

<item android:title="Search" android:icon="哪个可画? "/>

每次在Light和Dark之间切换应用程序主题时,我是否必须更新所有这些可绘制的引用?

S.D*_*.D. 74

有一种方法可以将android drawables(以及res/values中的许多其他元素)定义为依赖于Theme.

让我们假设我们有两个drawables,在这种情况下菜单图标:

res/drawable/ic_search_light.png
res/drawable/ic_search_dark.png
Run Code Online (Sandbox Code Playgroud)

我们想要使用ic_search_dark.png默认的应用程序主题Theme或扩展它,同样,ic_search_light.png如果我们的应用程序主题更改为默认Theme.Light或某些主题扩展它,我们想要.

/res/attrs.xml中定义具有唯一名称的常规属性,如:

<resources>
<attr name="theme_dependent_icon" format="reference"/>
</resources>
Run Code Online (Sandbox Code Playgroud)

这是一个全局属性和格式类型是引用,如果是自定义视图,它可以与样式属性一起定义:

<resources>
    <declare-styleable name="custom_menu">
        <attr name="theme_dependent_icon" format="reference"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

接下来,在res/styles.xmlres/themes.xml中定义两个主题,扩展默认值ThemeTheme.Light(或从中继承的主题):

<resources>
    <style name="CustomTheme" parent="android:Theme">
        <item name="theme_dependent_icon" >@drawable/ic_search_dark</item>
    </style>

    <style name="CustomTheme.Light" parent="android:Theme.Light">
        <item name="theme_dependent_icon" >@drawable/ic_search_light</item>
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

最后,使用我们定义的引用属性来引用这些图标.在这种情况下,我们在定义菜单布局时使用

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Menu Item"  android:icon="?attr/theme_dependent_icon"/>
</menu>
Run Code Online (Sandbox Code Playgroud)

?attr 指的是当前主题的属性.

现在,我们可以使用以上两个主题进行应用:

<application android:theme="@style/CustomTheme">
Run Code Online (Sandbox Code Playgroud)

要么

<application android:theme="@style/CustomTheme.Light">
Run Code Online (Sandbox Code Playgroud)

并相应地使用相应的资源.

通过在Activity的最开头设置主题,也可以在Code中应用主题onCreate().

UPDATE

此答案中解释了从代码访问这些依赖于主题的资源的方法.