在RecyclerView中为棒棒糖之前的可绘制着色 [英] Drawable tinting in RecyclerView for pre-Lollipop

查看:84
本文介绍了在RecyclerView中为棒棒糖之前的可绘制着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 RecyclerView

Drawable likeDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up);
Drawable likeWrappedDrawable = DrawableCompat.wrap(likeDrawable);
DrawableCompat.setTint(likeWrappedDrawable,ContextCompat.getColor(getActivity(), android.R.color.white));
holder.ivLike.setImageDrawable(likeWrappedDrawable);

现在所有这些操作都在RecyclerView适配器的 onBindViewHolder 中完成

Now all of this is being done in the onBindViewHolder of the RecyclerView Adapter

我根据该列表项的状态在三种颜色之间更改此色调.对于Lolipop及更高版本,这一切正常,但在此版本以下,列表项目的颜色是无法预测的.有时它显示正确的颜色,但刷新列表时有时会更改为其他颜色.

I change this tint between three colors based on the state of that list item. This works all fine for Lolipop and above but below this version, the color of the list item is unpredictable. Sometimes it shows the right color but on refreshing the list sometimes it changes to some other color.

在这种情况下,我在这里做错的任何事情还是棒棒糖上的着色仍然无法使用?

Anything im doing wrong here or the tinting thing on pre-lollipop is still unusable in this particular case?

包括我的 onBindViewHolder

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    Drawable likeDrawable =
        ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up);

    Drawable likeWrappedDrawable = DrawableCompat.wrap(likeDrawable);

    holder.tvLikeCount.setTextColor(ResUtil.getColor(R.color.light_font,
        getActivity()));

    DrawableCompat.setTint(likeWrappedDrawable,
        ContextCompat.getColor(getActivity(), android.R.color.white));

    if (tweetModel.isFavorited()) {
        DrawableCompat.setTint(likeWrappedDrawable,
            ContextCompat.getColor(getActivity(), android.R.color.holo_blue_light));
    }

    holder.ivLike.setImageDrawable(likeWrappedDrawable);

}

推荐答案

在调用setTint()之前,在Drawable上调用mutate()

Call mutate() on the Drawable before calling setTint()

Drawable likeDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_thumb_up).mutate();

默认情况下,从同一资源加载的所有drawable实例都具有相同的状态;如果您修改一个实例的状态,则所有其他实例将收到相同的修改. http://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()

By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. http://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()

这篇关于在RecyclerView中为棒棒糖之前的可绘制着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆