velis
velis

Reputation: 10025

Android theming: Can I just set alpha value to an existing color?

So if I'm defining a style for some widget and want to set text color to some predetermined color + some transparency. Normally, I'd define it like this (oversimplified):

<item name="android:textColor">#a0ffffff</item>

However, I'd like to be able to do it like this:

<color name="textTitle">#ffffff</color>
<item name="android:textColor">#a0 | @color/textTitle</item>
<item name="android:someotherColor">#70 | @color/textTitle</item>

I'd like that #a0 and #70 to mean my desired transparency while the @color... represents some predefined color (which I may not know because it's ROM specific)

What's the best way to do this?

Upvotes: 2

Views: 629

Answers (2)

Aleksandar Ilic
Aleksandar Ilic

Reputation: 1546

Support library has helper method ColorUtils.setAlphaComponent(int color, int alpha).

Here is the source.

/**
 * Set the alpha component of {@code color} to be {@code alpha}.
 */
public static int setAlphaComponent(int color, int alpha) {
    if (alpha < 0 || alpha > 255) {
        throw new IllegalArgumentException("alpha must be between 0 and 255.");
    }
    return (color & 0x00ffffff) | (alpha << 24);
}

Upvotes: 1

vipluv
vipluv

Reputation: 607

You could set the color to @color/textTitle directly where you want to use it and use android:alpha to set the alpha value separately.

Upvotes: 1

Related Questions