更改主题时仅更改颜色

时间:2017-07-04 08:29:26

标签: android android-resources android-theme android-styles android-color

我想在我的Android应用程序中支持不同的主题。 主题应该只有两种颜色不同。因此每个主题都有这些颜色:

  • 原色
  • 二次色

我想要的是,有一个大的默认主题,也有像按钮样式等子项,像这样(styles.xml):

<style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="homeAsUpIndicator">@drawable/my_stackoverflow_arrow</item>
    [...]
</style>

<style name="DefaultTheme.NoActionBar">
    <!-- hide action bar and title -->
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="DefaultTheme.Button">
    <item name="android:textAllCaps">true</item>
    <item name="android:textStyle">bold</item>
    [...]
</style>

但现在我也想改变不同颜色的主题。因此,我在attrs.xml文件中创建了一个资源:

<resources>
    <attr name="ThemeColorPrimary" format="reference" />
    <attr name="ThemeColorSecondary" format="reference" />
</resources>

所以现在我可以在我的styles.xml中使用此属性,如下所示:

<style name="DefaultTheme.Button">
    <item name="android:textAllCaps">true</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?attr/ThemeColorPrimary</item>
    [...]
</style>

但是如何创建彩色主题?我知道我需要做这样的事情:

<item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>

但是在哪里?哪个主题继承自哪个?如果我现在有类似的东西:

<style name="BlueTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlueSecondary</item>
</style>

<style name="GreyTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeGreyPrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeGreySecondary</item>
</style>

<style name="BlackTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeBlackPrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlackSecondary</item>
</style>

我无法在AndroidManifest.xml中指定这样的主题:

<activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/DefaultTheme.NoActionBar" />

因为缺少指定的资源。否则我也不能这样:

<activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/BlueTheme.NoActionBar" />

因为BlueTheme没有被称为“NoActionBar”的Child。

我知道这很令人困惑,我自己很困惑。 我怎么解决这个问题? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您必须在父主题中指定这些自定义属性:

<style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="ThemeColorPrimary">@color/defaultPrimaryColor</item>
    <item name="ThemeColorSecondary">@color/defaultSecondaryColor</item>
</style>

然后DefaultTheme的每个孩子都可以访问您的自定义属性,也可以覆盖这些属性。

如果您要合并NoActionBarBlueTheme,那么您必须继承NoActionBar主题:

<style name="BlueNoActionBarTheme" parent="DefaultTheme.NoActionBar">
    <item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlueSecondary</item>
</style>
相关问题