Dynamically Tint drawable in adapter change color for all

試著忘記壹切 提交于 2020-08-11 03:06:05

问题


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.

Here my code in adapter:

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    // Get item from position
    MyObject object = array_data.get(position);
    ...
    ...
    Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_beenhere_black_24dp);
    Drawable wrappedDrawable;
    if (unwrappedDrawable != null) {
        wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
        DrawableCompat.setTint(wrappedDrawable, object.getMyColor());
        holder.imvPreparationTime.setImageDrawable(wrappedDrawable);
    }

Unfortunately the behavior is not correct. All drawable of items in recyclerview have the same color together and it change for all during scroll.

How can I perform my goal? I want that every items have his own color and not change.


回答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) {
                        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
                        Drawable mutableDrawable = 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 :

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

Happy Coding!




回答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.



来源:https://stackoverflow.com/questions/58499495/dynamically-tint-drawable-in-adapter-change-color-for-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!