RecyclerView BackgroundColor [英] RecyclerView BackgroundColor

查看:397
本文介绍了RecyclerView BackgroundColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 RecyclerView 显示一些文本数据。

I used a RecyclerView to display some text data. I got the logic in it to select different cards.

我想更改所选卡片的外观。

I would like to change the appearance of the selected cards.

public void toggleSelection(int pos)
    {
        RecyclerView.ViewHolder viewHolder = recView.findViewHolderForPosition(pos);
        if (selectedItems.get(pos, false)) {
            selectedItems.delete(pos);
            viewHolder.itemView.setBackgroundColor(Color.WHITE);
        }
        else {
            selectedItems.put(pos, true);
            viewHolder.itemView.setBackgroundColor(Color.GREEN);
        }
        notifyItemChanged(pos);
    }

如果我像这样使用我的代码。我的onClick事件触发此代码,我的卡片背景颜色变为绿色。

If I use my code like this it works. My onClick event triggers this code and my card background color changes to green.

这里是我的问题:向下滚动显示在相同的相对位置在列表中)具有相同的背景颜色,即使它们没有被选择;

So here is my problem: scrolling down shows other cards in the same relative position (but further down in the list) with the same background color even if they are not selected; selecting the first card and scrolling down to where the eighth card is the top visible card shows the eighth card highlighted.

推荐答案

您需要选择第一张卡片,并向下滚动到第八张卡片是最顶部的可见卡片。以在 onBindViewHolder()方法中显式设置颜色。

回收站视图名称建议回收视图,因此第0项作为您案例中的第8个项目回收。它们使用与使用 onCreateViewHolder()方法创建的相同的视图持有者。每当任何一个查看 onBindViewHolder()方法。


我建议您在数据模型中创建一个额外的布尔字段,告诉您是否突出显示了视图。您应该在 toggleSelection()中切换它。
然后在 onBindViewHolder()中检查此字段的值并相应地设置颜色。

You need to set the colors explicitly in onBindViewHolder() method.

A recycler view as the name suggests recycles views, so 0th item is recycled as the 8th item in your case. They use the same view holder created using the onCreateViewHolder() method.And each time any one of them comes into view the onBindViewHolder() method is called.

I suggest you create an additional boolean field in your data model, telling you whether you've highlighted the view or not. You should toggle it in toggleSelection(). Then in the onBindViewHolder() you check the value of this field and set your color accordingly.

这篇关于RecyclerView BackgroundColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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