DEV Community

leminhduc1202
leminhduc1202

Posted on

Answer: Changing background color of selected item in recyclerview

Can be better, but it works.

int selectedPosition = -1
int lastSelectedPosition = -1;
public void onBindViewHolder(final ViewHolder holder, final int position) {
  holder.binding.getRoot().setOnClickListener(v -> {
    lastSelectedPosition = selectedPosition;
    selectedPosition = holder.getBindingAdapterPosition();
    notifyItemChanged(lastSelectedPosition);
    notifyItemChanged(selectedPosition);
  });
  if (selectedPosition == holder.getBindingAdapterPosition()) {
    holder.binding.linearLayout.setCardBackgroundColor(Color.LTGRAY);
  } else {
    holder.binding.linearLayout.setCardBackgroundColor(Color.WHITE);
  }

}
public class ViewHolder

Top comments (0)