问题
I am working on a "dynamic change theme" function of my app (light and dark).
I have some special customized widget which is using special color. And I also want to specify the color of this widget in theme attributes.
For example, I want to set an attribute in the theme like
<item name="MySpecialTextColor">@color/white</item>
In the layout, how can I set the text color of the TextView?
<TextView
...
android:color="XXXX????"
...
/>
How can I achieve this?
回答1:
First, define two colors in /res/values/colors.xml
:
<resources>
<!-- ActionBar-->
<color name="MySpecialTextColorLight">@color/white</color>
<color name="MySpecialTextColorDark">@color/black</color>
<resources>
Then define an attribute with a unique name in /res/values/attrs.xml
:
<resources>
<attr name="mytheme_text_color" format="color"/>
</resources>
Next, define value for this attribute in your two themes, like:
<resources>
<style name="MyTheme" parent="android:Theme">
<item name="mytheme_text_color">@color/MySpecialTextColorDark</item>
</style>
<style name="MyTheme.Light" parent="android:Theme.Light">
<item name="mytheme_text_color">@color/MySpecialTextColorLight</item>
</style>
</resources>
Finally, use the reference attribute you define to refer to these colors. In your case, you use:
<TextView
...
android:color="?attr/mytheme_text_color"
.../>
来源:https://stackoverflow.com/questions/23536264/android-how-to-specify-special-attribute-to-some-specific-view-in-different-th