RecyclerView causes issue when recycling

后端 未结 3 657
深忆病人
深忆病人 2020-12-01 12:52

I have a list of items that I created using RecyclerView. When the user clicks on one of them I change the background color of that selected item. The problem i

3条回答
  •  清歌不尽
    2020-12-01 13:41

    This is quite a common mistake that has an easy solution.

    Quick answer: add this line in your onBindViewHolder method:

    if (orderItem.isSelected()){
        viewHolder.orderItem.setBackgroundColor(Color.parseColor(SELECTED_COLOR));
    } else {
        viewHolder.orderItem.setBackgroundColor(Color.parseColor(DEFAULT_COLOR));
    }
    

    (with DEFAULT_COLOR the color that the viewholder has by default)

    Explained answer: when the system recycles a viewholder it just calls onBindViewHolder method so if you have changed anything of that viewholder you'll have to reset it. This will happen if you change background, item's position, etc. Any change that is not related to content per se should be reset in that method

提交回复
热议问题