android - 在 RecyclerView 中为 pre-Lollipop 绘制着色

标签 android android-drawable android-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 Adapter 的 onBindViewHolder 中完成

我根据该列表项的状态在三种颜色之间更改此色调。这适用于 Lolipop 及更高版本,但在此版本以下,列表项的颜色不可预测。有时它会显示正确的颜色,但在刷新列表时有时会变成其他颜色。

我在这里做错了什么,或者 Lollipop 之前的着色在这种特殊情况下仍然无法使用?

更新

包括来 self 的 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()

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

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

关于android - 在 RecyclerView 中为 pre-Lollipop 绘制着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224899/

相关文章:

android - 使用android相机时如何删除图库中的重复图片?

android - SQLite,基于列中的较高值合并两个表

android - EditText 中的 Drawable 会导致 Activity 崩溃

java - 从文件路径创建位图/可绘制对象

android - RecyclerView 更改数据集

android - RecyclerView 项目有时无法正确显示,直到我滚动(仅在 Genymotion 平板电脑上)

android - 将 RecyclerView 与来自 LoaderManager 的数据一起使用

android - 如何插入到多对多关系中。 SQLite

android - 如何在 AlertDialog 中为 EditText 设置边距

android - 如何在android中制作药丸形按钮?