在一些网格项目上设置不同的颜色

Setting different color on some grid items

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

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 项目设置不同的颜色?

改变这个:

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

对此:

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

当您处理 RecyclerView 时,请务必了解您的 ViewHolder 将被 回收 重新使用。因此,如果您希望某事发生 "sometimes,",您需要确保在 "sometimes" 未发生时始终将状态设置回默认状态。

这是回收视图的本质,甚至当您对普通列表视图使用旧方法时也是如此。您面临的问题是您实际上并没有回收视图。回收视图将传递包含需要回收的旧视图的视图持有者。换句话说,当您滚动时,您将收到以前设置为绿色的视图,现在需要设置为白色(或您想要的任何颜色)。请记住,如果您之前收到视图 xyz 的视图持有者,则无法保证下次滚动到该视图时您会收到相同的持有者。它可以是不同的。

你展示的逻辑:

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

是正确的,但是您要回收的物品应该是白色背景(或任何其他颜色)?这些未设置,但必须设置。

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

这样可以确保正确回收每个视图的背景。现在,这里所说的背景适用于视图持有者中的任何视图,包括图像 - 它们必须正确设置 a.k.a。回收 - 这就是它被称为回收视图的原因。

您需要在 onBindViewHolder() 方法中添加 else 语句

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