Android Use custom themes to modify style attributes

谁都会走 提交于 2019-12-18 08:49:36

问题


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:


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



来源:https://stackoverflow.com/questions/29524543/android-use-custom-themes-to-modify-style-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!