Android - how to specify special attribute to some specific view in different theme

妖精的绣舞 提交于 2019-12-13 00:09:31

问题


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

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