Here I clicked on the item to change item background and color. I\'ve stored the clicked item value in the database and change the layout color and text color and recreating the
Note:
onBindViewHolder()
is not a place to implement the click listeners, but I am just providing you the logic for how to implement single selection inrecyclerView
.
Now lets jump to the solution,
simply follow the below tutorial and change the variable, fields, and background according to your need, you have to implement the below method in onBindViewHolder()
method of RecyclerView
First, initialize the lastClickedPosition and isclicked
int lastPositionClicked = -1;
boolean isClicked = false;
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
holder.YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// store the position which you have just clicked and you will change the background of this clicked view
lastPositionClicked = position;
isClicked = true;
// need to refresh the adapter
SlabAdapter.this.notifyDataSetChanged();
}
});
// only change the background of last clicked item
if (isClicked && position == lastPositionClicked) {
// change clicked view background color
} else {
// otherwise set the default color for all positions
}
}
let me know if this works.