sergii.gudym sergii.gudym - 3 months ago 11
Android Question

Custom color kit by Style

How create custom colors kit by themes?


  • in styles.xml

    <style name="Dark" parent="@style/Theme.AppCompat">
    <item name="blueStyled">#229</item>
    </style>

  • in values-v21/colors.xml

    <color name="blueStyled">?blueStyled</color>



but app crashes when try to set this color, e.g.:
android:background="@color/blueStyled"

Answer

First, define your colors in res/values/colors.xml:

<color name="dark_color">#229</color>
<color name="light_color">#6161ff</color>

Create the attribute you're gonna use as your color in /res/attrs.xml:

<resources>
    <attr name="blue_styled" format="reference"/>
</resources>

Define items in your styles with the same name as the name of the attribute and the desired colors as their values:

<style name="Dark" parent="@style/Theme.AppCompat">
     <item name="blue_styled">@color/dark_color</item>
</style>

<style name="Light" parent="@style/Theme.AppCompat.Light">
     <item name="blue_styled">@color/light_color</item>
</style>

Use the attribute as your background:

android:background="?attr/blue_styled"

The attribute should get resolved to the appropriate color based on the theme.

Comments