Android: Changing TextView alpha transparency across different target SDKs

Sometimes you may need to make a TextView (label) look a little transparent to make emphasis on other parts of your UI. The .setAlpha() function on TextView is not supported after later in the SDK. Here’s a static workaround you can place on some sort of UIUtils class you may have in your project.

[java]
/**
* Android devices with SDK below target=11 do not support textView.setAlpha().
* This is a work around.
* @param v – the text view
* @param alpha – a value from 0 to 255. (0=transparent, 255=fully visible)
*/
public static void setTextViewAlpha(TextView v, int alpha) {
v.setTextColor(v.getTextColors().withAlpha(alpha));
v.setHintTextColor(v.getHintTextColors().withAlpha(alpha));
v.setLinkTextColor(v.getLinkTextColors().withAlpha(alpha));

Drawable[] compoundDrawables = v.getCompoundDrawables();
for (int i=0 ; i < compoundDrawables.length; i++) { Drawable d = compoundDrawables[i]; if (d != null) { d.setAlpha(alpha); } } } [/java] Enjoy, and above all CODE!

Leave a Reply

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