Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recycler view item colour change repeating after scrolling

Recycler view item color change repeating after scrolling.

I used to change color at a particular position of the Recyclerview list. When scrolling occurs another item at the bottom has the same change. And it is repeating in pattern. How to resolve this?

 holder.recycle_Listing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            itemListener.connectionClicked(v,position, itemtype);

            holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));

        }
    });
like image 909
SARATH V Avatar asked Mar 08 '23 18:03

SARATH V


2 Answers

The recycler view recycles the view in OnBindViewHolder.So when items are clicked it gets reflected in some other positions.To solve this. create a global SparseBooleanArray to store the clicked position.

private final SparseBooleanArray array=new SparseBooleanArray();

Then inside final viewholder add the clickListener and onClick store the position of the clicked item.

public class ViewHolder extends RecyclerView.ViewHolder {
    public YOURVIEW view;
    public ViewHolder(View v) {
        super(v);
        view = (YOURVIEW) v.findViewById(R.id.YOURVIEWID);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                array.put(getAdapterPosition(),true);
                notifyDataSetChanged();
            }
        });
    }
}

And in inside OnBindViewHolder,

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    if(array.get(position)){
        holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
    }else{
        holder.mainlayout.setBackgroundColor(UNSELECTEDCOLOR);
    }
}
like image 158
Sharath kumar Avatar answered Mar 10 '23 10:03

Sharath kumar


I think you can set your background color in void onBindViewHolder(VH holder, int position); such as

List<Integer> selectedPosition = new ArrayList(yourDataSize);
void onBindViewHolder(VH holder, int position){

     if(selectedPosition.get(position) == 1){
       holder.mainlayout.setBackgroundColor(Color.parseColor("#e927a4d1"));
     }else {
       holder.mainlayout.setBackgroundColor(normalColor);
     }

     //when the item clicked 
     selectedPosition.add(position,1);

}
like image 24
CoXier Avatar answered Mar 10 '23 10:03

CoXier