【问题标题】:Android Use custom themes to modify style attributesAndroid 使用自定义主题修改样式属性
【发布时间】:2015-04-08 20:18:03
【问题描述】:

我想创建两个主题,GrayTheme 和 RedTheme,它们修改一个样式属性。例如这是我的两个主题,默认字体颜色是白色,这对两个主题都很好:

<style name="RedTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textColor">@color/white</item>
</style>

<style name="GrayTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textColor">@color/white</item>
</style>

但我有一种用于 Header TextViews 的样式。如果我使用 RedTheme,我希望 HeaderFont 样式的 textColor 为红色,如果是 GrayTheme,我希望 HeaderFont textColor 为灰色,而无需修改访问此 HeaderFont 样式的各个 xml 文件。

<style name="HeaderFont" parent="@android:style/TextAppearance.Medium">
    <item name="android:textColor">@color/gray</item>
</style>

我一直在寻找一个优雅的解决方案,但没有找到任何东西。想法?

【问题讨论】:

    标签: android android-theme android-styles


    【解决方案1】:

    在寻找干净的解决方案多次失败后,我终于找到了一个很好用的答案。

    我创建了一个自定义属性 headerFontColor 并将其添加到 /res/values/attrs.xml

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

    接下来,在 HeaderFont 的样式中,我添加了将 textColor 更新为新的自定义属性 (headerFontColor) 而不是特定颜色

    <style name="HeaderFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">?headerFontColor</item>
    </style>
    

    现在,我可以简单地根据主题设置 headerFontColor 属性

    <style name="RedTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/white</item>
        <item name="headerFontColor">@color/red</item>
    </style>
    <style name="GrayTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/white</item>
        <item name="headerFontColor">@color/gray</item>
    </style>
    

    完成此操作后,所有使用 HeaderFont 样式的 TextView 只需切换主题即可使用 headerFontColor 进行更新

    这个解决方案指导了我:Setting a color based on theme

    【讨论】:

    • 你把自定义属性放在什么文件里?
    • 我在值目录 /res/values/attrs.xml @KennethWorden 中创建了一个属性文件
    • 这完美无瑕,并为基于黑暗/夜间模式的自定义颜色选择打开了新的大门。非常感谢!
    【解决方案2】:

    我使用了来自 google 的 iosched 项目的参考资料。

    在 res/values/ 中创建了 attrs.xml 文件

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
      <declare-styleable name="Theme">
        <attr name="headerFontColor" format="color" />
      </declare-styleable>
    </resources>
    

    然后在themes.xml中

    <style name="RedTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
      <item name="headerFontColor">@color/red</item>
    </style>
    
    <style name="GrayTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
      <item name="headerFontColor">@color/gray</item>
    </style>
    

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多