Is there a function to increase transparency from a colour resource in Android's XML?-ThrowExceptions

Exception or error:

I have a colour resource below:

<color name="colorPrimary">#546e7a</color>

I want to set this color resource as the color of many text types of my customized themes. However, on each theme, I may want to alter the transparency value (i.e. the a in rgba) of my colour resource. If possible, I do not want to redefine a new colour resource like below (simply because I might use a lot of different transparency values):

<color name="colorPrimary12Percent">#1FD81B60</color>

Is there some sort of function in XML that can alter the transparency of a colour resource value given the colour resource and the transparency value (e.g. rgba(colorResourceValue, transparencyValue))? An example of what I want to do with said function:

<style name="SomeNewStyle" parent="InheritFromThis">
    <item name="android:textColor">rgba(@color/colorPrimary, 12%)</item> <!-- This is what I want -->
How to solve:

Try the ColorStateList. You can find a useful description in Android Styling: Prefer Theme Attributes.

A ColorStateList can do the combining of the text color and the alpha value by theme/style as follows:

Define a custom attribute that will hold the alpha value:

    <declare-styleable name="MyAttrs">
        <attr name="textAlpha" format="float" />

Define the ColorStateList:

    <item android:alpha="?attr/textAlpha" android:color="?attr/colorPrimary" />

Put it all together in styles:

<style name="AppTheme">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="textAlpha">0.5</item>
    <item name="android:textColor">@drawable/color_state_list_example</item>

If you want to change the color by style and not use colorPrimary, you can define an additional attribute to hold the color like the one for the alpha value.

Leave a Reply

Your email address will not be published. Required fields are marked *