How to properly DEselect an item on RecyclerView?

Viewed 2660

I followed this answer: https://stackoverflow.com/a/30046476/8793443 and got it to work: only one item is selected at a time (which is what I want).

However, when the same item is clicked for a second time, it remains selected. How can I deselect it so that it goes back to it's original color background?

Any help is appreciated. Thanks!

1 Answers

The OnClick event must be this instead:

@Override
public void onClick(View view) {
  if (selectedPos == getAdapterPosition()) {
    selectedPos = RecyclerView.NO_POSITION;
    notifyDataSetChanged();
    return;
  }
  selectedPos = getAdapterPosition();
  notifyDataSetChanged();
}

It works like a charm! Thanks to Quick learner's answer for inspiration.

Related