Setting the Color of a TextView Drawable for Android
@kylewbanks on Feb 15, 2016.
Written by Hey, if you didn't already know, I'm currently working on an open world stealth exploration game called Farewell North in my spare time, which is available to wishlist on Steam!
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!