使用自定义主题修改Android样式属性

10

我想创建两个主题,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>

但我有一种用于标题TextView的样式。 如果我正在使用RedTheme,我希望HeaderFont样式具有红色textColor,如果是GrayTheme,则希望HeaderFont textColor为灰色,而无需我修改访问此HeaderFont样式的单个xml文件。

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

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

2个回答

26

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

我创建了一个自定义属性 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

这个解决方案指引了我:根据主题设置颜色


你把自定义属性放在哪个文件里了? - Kenny Worden
4
我已经在/res/values/attrs.xml目录下创建了一个属性文件。@KennethWorden - Marc
这个功能完美无缺,为基于暗/夜间模式的自定义颜色选择打开了新的大门。非常感谢! - Suhel Chakraborty

0
我使用了谷歌的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>

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