Kyle Banks

Setting the Color of a TextView Drawable for Android

Written by @kylewbanks on Feb 15, 2016.

The Android TextView supports displaying a drawable beside, above, or below the text, but how do you programatically change the color of the drawable to match the text? Turns out it's actually really easy using a PorterDuffColorFilter, but a little obscured behind some silly documentation.

There's a great explanation of the PorterDuffColorFilter over at Softwyer, but for our purposes we only care about the SRC_IN PorterDuff Mode.

What we'll do is iterate over the drawables of a TextView and apply the filter to each:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView txt = (TextView) findViewById(R.id.my_textview);
        setTextViewDrawableColor(txt, R.color.my_color);
    }

    private void setTextViewDrawableColor(TextView textView, int color) {
        for (Drawable drawable : textView.getCompoundDrawables()) {
            if (drawable != null) {
                drawable.setColorFilter(new PorterDuffColorFilter(getColor(color), PorterDuff.Mode.SRC_IN));
            }
        }
    }

And there you have it, a very simple method to apply a color filter to a TextView's drawable.

Let me know if this post was helpful on Twitter @kylewbanks or down below!