首页 > 解决方案 > 在某些网格项目上设置不同的颜色

问题描述

我想根据天气设置不同的网格项目背景颜色,该项目的模型有一些布尔值设置为真或假。所以在我的onBindViewHolder方法中我MyRecyclerviewAdapter检查:

if (current.hasWiki()) {
        holder.linearLayout.setBackgroundColor(0xCCF0FCC0);
    } 

加载回收器网格视图时,它看起来很好,具有 hasWiki==true 的项目被着色为绿色,而 hasWiki==false 则根本没有着色。但是当我向下滚动并且那些未着色的项目不再显示在屏幕上时,我再次向上滚动并且这些应该是未着色的项目现在被着色为绿色。这一切都搞砸了。

这是我的 MyViewHolder:

public MyViewHolder(View itemView) {
        super(itemView);
        linearLayout = (LinearLayout)itemView.findViewById(R.id.rootLayout);
}

那么,我该如何解决这些不良行为呢?是否有另一种方法可以根据一些任意标志为 recyclerview 项目设置不同的颜色?

标签: androidandroid-layoutandroid-recyclerviewrecyclerview-layout

解决方案


改变这个:

if (current.hasWiki()) {
    holder.linearLayout.setBackgroundColor(0xCCF0FCC0);
} 

对此:

if (current.hasWiki()) {
    holder.linearLayout.setBackgroundColor(0xCCF0FCC0);
} else {
    holder.linearLayout.setBackgroundColor(/* default color here */);
}

当您处理s 时RecyclerView,重要的是要了解您ViewHolder的 s 将被回收重复使用。因此,如果您希望某事“有时”发生,您需要确保在“有时”没有发生时始终将状态设置回默认值。


推荐阅读