20

Is there a way to reference a color resource with modified alpha value in a xml resource file? What I'm looking for is something like this:

<!-- base color -->
<color name="myColor">#19AEE0</color>
<!-- redefined color with alpha - not particularly elegant -->
<color name="myColor2">#8019AEE0</color>
<!-- referenced color with alpha -->
<color name="myColorTransparent" alpha="0.5">@color/myColor</color>

I am aware that this can be easily done programmatically, but doing it the declarative way would be much clearer and more readable when defining several transparency values for the same color.

SpaceBison
  • 2,525
  • 1
  • 21
  • 38

1 Answers1

6

After searching around a bit to set the color accent as the ripple drawable's color, I've found that it can be done with the aid of a <selector>.

Add a color resource folder if not existing and create a new file there, whose base name will be used as color resource. For example, name it my_color_transparent.xml. Then, paste the following contents.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:color="@color/myColor"
        android:alpha=".5" />
</selector>

At this point, you can reference it as @color/my_color_transparent via XML or programmatically as usual, like colors in the values folder.

NOTE: The android:alpha attribute is applied as a mask, so the alpha is multiplied by that of the color specified via the android:color attribute. As an instance, if @color/myColor were 20% opaque and android:alpha were .5, then the opacity of @color/my_color_transparent would be 10%.

Davide Cannizzo
  • 2,826
  • 1
  • 29
  • 31
  • This solution will only work on API 23 and above https://developer.android.com/reference/android/content/res/ColorStateList#item-attributes – akaMahesh Feb 06 '23 at 12:33