Skip to content Skip to sidebar Skip to footer

Dynamically Tint Drawable In Adapter Change Color For All

I get an array of strings from my server using a volley connection. Every single string contain a different color in hex. I use this color to set Tint of a drawable in adapter. Her

Solution 1:

This can be done using Drawable.mutate() . In your adapter class, onBindViewHolder(..) block, use below code snippet to change the tint color of your drawable -

for (Drawable drawable : myTextView.getCompoundDrawablesRelative()) {
                    if (drawable != null) {
                        DrawablewrappedDrawable= DrawableCompat.wrap(drawable);
                        DrawablemutableDrawable= wrappedDrawable.mutate();
                        DrawableCompat.setTint(mutableDrawable, ContextCompat.getColor(context, R.color.desiredColor));
                    }
                }

Note : This code snippet I've used to change the tint of textview's drawable. So, if you required to change the tint of image or drawable file, simply do it as :

DrawablewrappedDrawable= DrawableCompat.wrap(drawable);
                        DrawablemutableDrawable= wrappedDrawable.mutate();
                        DrawableCompat.setTint(mutableDrawable, ContextCompat.getColor(context, R.color.colorGrayD5));

Happy Coding!

Solution 2:

Since recyclerView is reusing items there is often such a behaviour. Easiest way is to put if else for view you want to set tint for. E.g.

if (unwrappedDrawable != null) {
        wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
        DrawableCompat.setTint(wrappedDrawable, object.getMyColor());
        holder.imvPreparationTime.setImageDrawable(wrappedDrawable);
    } else {
        holder.imvPreparationTime.setImageDrawable(<Some Other drawable, for example default one>);
    }

The idea is to force recycler view draw something on item and not to reuse already set one.

Post a Comment for "Dynamically Tint Drawable In Adapter Change Color For All"