As noted in this linked question, setting listeners for viewHolders should be done in onCreateViewHolder. That said, the implementation below was originally aimed at multiple selection, but I threw a hack in the snippet to force single selection.(*1)
// an array of selected items (Integer indices)
private final ArrayList<Integer> selected = new ArrayList<>();
// items coming into view
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// each time an item comes into view, its position is checked
// against "selected" indices
if (!selected.contains(position)){
// view not selected
holder.parent.setBackgroundColor(Color.LTGRAY);
}
else
// view is selected
holder.parent.setBackgroundColor(Color.CYAN);
}
// selecting items
@Override
public boolean onLongClick(View v) {
// select (set color) immediately.
v.setBackgroundColor(Color.CYAN);
// (*1)
// forcing single selection here...
if (selected.isEmpty()){
selected.add(position); // (done - see note)
}else {
int oldSelected = selected.get(0);
selected.clear(); // (*1)... and here.
selected.add(position);
// note: We do not notify that an item has been selected
// because that work is done here. We instead send
// notifications for items which have been deselected.
notifyItemChanged(oldSelected);
}
return false;
}