3

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!

W. Stalin R.
  • 81
  • 1
  • 8
  • Have you tried using isSelected()? – Ayush Khare Nov 08 '18 at 07:03
  • Yes. Unfortunately, I haven't figured out how to make it work given the way it's done on the example from my link. That is, `notifyItemChanged(selectedPos)` is used twice (once with the previous position and then with the current position). However, when the same item is selected, `onBindViewHolder` only gets called once. How do you suggest using `isSelected()`? – W. Stalin R. Nov 08 '18 at 14:20

1 Answers1

4

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.

W. Stalin R.
  • 81
  • 1
  • 8