androidandroid-resourcesandroid-color

How do I add an alpha channel to an existing Android color in xml


I have the following color in values/colors.xml:

<color name="grey_1">#0F0E10</color>

I want to reference this color in a gradient:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="#000F0E10"
        android:endColor="#990F0E10"/>
</shape>

However, this duplicates the RGB color definition. Ideally, I'd like to write something like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="alpha(00, @color/grey_1)"
        android:endColor="alpha(99, @color/grey_1)"/>
</shape>

or this:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="@color/grey_1"
        android:startTransparency="#00"
        android:endColor="@color/grey_1"
        android:endTransparency="#99"/>
</shape>

Is this possible?


Solution

  • You have to do it in code. You can get a color like this,

    int color = getResources().getColor(R.color.<the color>);
    

    You can turn it into ARGB like this:

    int a = Color.alpha(color);
    int r = Color.red(color);
    int g = Color.green(color);
    int b = Color.blue(color);
    

    Now you can re-create the color with whatever alpha you want:

    color = Color.argb(<new alpha>, r, g, b);
    

    This means of course you'd need to construct your drawable from code. Not as clean but possible.