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.
The name of the XML tag is all that matters under values folder. Here the name of the tag is color . So you can access it using @color/ .
Use ResourcesCompat. getColor(App. getRes(), R. color.
colors. xml is an XML file which is used to store the colors for the resources. An Android project contains 3 essential colours namely: colorPrimary. colorPrimaryDark.
An integer defined in XML. Note: An integer is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine integer resources with other simple resources in the one XML file, under one <resources> element. The filename is arbitrary.
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%.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With