androidcompatibilitytint

Android: Tint using DrawableCompat


I'm trying to tint an image prior to Android API level 21. I've successfully tinted items using:

<android:tint="@color/red"/>

However, I can't seem to figure out how to do this through code on an ImageView:

Drawable iconDrawable = this.mContext.getResources().getDrawable(R.drawable.somedrawable);
DrawableCompat.setTint(iconDrawable, this.mContext.getResources().getColor(R.color.red));
imageView.setImageDrawable(iconDrawable);

I've tried setting the TintMode but this seems to make no different. Am I using the v4 compatibility class DrawableCompat incorrectly?


Solution

  • The simplest way to tint cross-platform (if you don't need a ColorStateList) is:

    drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    

    Don't forget to mutate the Drawable before applying the filter.