RecyclerView BackgroundColor

≯℡__Kan透↙ 提交于 2019-12-06 07:59:40

问题


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);
    }

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.


回答1:


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.



来源:https://stackoverflow.com/questions/30836840/recyclerview-backgroundcolor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!