Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DrawableCompat setTint not working on API 19

I am using the DrawableCompat for tinting drawable as below, tinting doesn't seem to be working on API 19. I am using the support lib version 23.3.0

Drawable drawable = textView.getCompoundDrawables()[drawablePosition]; if (drawable != null) {         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {             drawable.setTint(color);         } else {             DrawableCompat.setTint(DrawableCompat.wrap(drawable), color);         }     } 
like image 899
rahulrv Avatar asked Apr 20 '16 00:04

rahulrv


2 Answers

I had the same problem. I combined the posts in https://stackoverflow.com/a/30928051 and tried the APIs 17, 19, 21, 22, 23 and N Preview 3 with SupportLib 23.4.0 to find a solution.

Even if it is mentioned, that the compat-class will use a filter for pre-lollipop-devices (see https://stackoverflow.com/a/27812472/2170109), it's not working.

Now, I check the API myself and use the following code, which is working on all tested APIs (for 17 and up).

    // https://stackoverflow.com/a/30928051/2170109     Drawable drawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.vector));     image.setImageDrawable(drawable);      /*      * need to use the filter | https://stackoverflow.com/a/30880522/2170109      * (even if compat should use it for pre-API21-devices | https://stackoverflow.com/a/27812472/2170109)      */     int color = ContextCompat.getColor(context, R.color.yourcolor);     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {         DrawableCompat.setTint(drawable, color);      } else {         drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);     } 
like image 200
hardysim Avatar answered Sep 25 '22 17:09

hardysim


Works on API 15-25 using AppCompat Support Library (tested on 24.1.1 and above).

public static Drawable getTintedDrawable(@NonNull final Context context,                                          @DrawableRes int drawableRes, @ColorRes int colorRes) {     Drawable d = ContextCompat.getDrawable(context, drawableRes);     d = DrawableCompat.wrap(d);     DrawableCompat.setTint(d.mutate(), ContextCompat.getColor(context, colorRes));     return d; } 
like image 44
localhost Avatar answered Sep 23 '22 17:09

localhost