'change item color on click in recyclerview android

I am trying to change the color of the items on click when the action mode is active. The problem is that e.g if there are five items in a recyclerview and you click one, scroll down and select sixth item and destroy the action mode. The next time you start selecting, that sixth item has automatically changed its color without you selecting it. I don't know why it is happening.

public static List<ModelClass> items = new ArrayList<>();
boolean isSelectMode = false;
boolean isActionModeEnabled = false;
public static List<ModelClass> selectList = new ArrayList<>();


@Override
public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int
        position) {
    holder.bind(items.get(position));

    ModelClass modelClass  = items.get(position);


    if (modelClass.isChecked() && isActionModeEnabled){
       holder.row.setBackgroundColor(Color.GREEN);
       modelClass.setChecked(true);
    } else {
       holder.row.setBackgroundColor(Color.TRANSPARENT);
       modelClass.setChecked(false);
    }
}

public class MyViewHolder extends RecyclerView.ViewHolder{

    public MyViewHolder(@NonNull View itemView) {

       super(itemView);
       row = itemView.findViewById(R.id.row);

       public void bind(ModelClass model) {

        holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isActionModeEnabled) {
                isSelectMode = true;


                s = items.get(getAdapterPosition());
                if (!selectList.contains(s)){
                    selectList.add(s);
                    row.setBackgroundColor(Color.GREEN);
                    model.setChecked(true);
                } else {
                    selectList.remove(s);
                    row.setBackgroundColor(Color.TRANSPARENT);
                    model.setChecked(false);

                }
            } 
    });
}


Solution 1:[1]

The problem is going to be in your view holder binding:

if (modelClass.isChecked() && isActionModeEnabled){
   holder.row.setBackgroundColor(Color.GREEN);
   modelClass.setChecked(true);
} else {
   holder.row.setBackgroundColor(Color.TRANSPARENT);
   modelClass.setChecked(false);
}

Remember that view holders are reused. That means that they will retain their internal state unless you change them. Your item list will also remember its state. Make sure you cover all the possible states of the item list and the reused view holders in the code above: You are probably missing a combination.

I recommend that you set a break point in the code above to make sure it is doing what you want. It should become obvious to you once you take a closer look.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cheticamp