Android Use custom themes to modify style attribut

2020-02-14 05:02发布

I want to create two themes, GrayTheme and RedTheme, that modify one style attribute. For example here are my two themes, default font color is white, which is fine for both themes:

<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>

But I have a style that I use for Header TextViews. If I am using the RedTheme I want the style HeaderFont to have textColor red and if it is the GrayTheme I want the HeaderFont textColor to be gray, without me having to modify the individual xml files that access this HeaderFont style.

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

I've been searching around looking for a graceful solution to this, but haven't been able to find anything. Ideas?

1条回答
闹够了就滚
2楼-- · 2020-02-14 05:22

After many failures of finding a clean solution I finally found an answer that works beautifully.

I created a custom attribute

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

Then in the style I added the custom attribute

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

Then I simply added the new attribute to the themes

<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>

This solution guided me: Setting a color based on theme

查看更多
登录 后发表回答