0

I have a RecyclerView in which a selected number of items show a different background color.

It gave me with many views with different color.

I used the position of adapter to change color and later I found that position changes when scrolling.

So I gave a unique code to every object of the ArrayList. And I gave the program to change background color if the unique code matches the given code.

Like,

    uniqueCode = 5;

public void onBindViewHolder(//..){

    Object object = objectArrayList.get(i);

    if(object.uniqueCode() == uniqueCode  ){
        holder.layout.setBackgroundColor(//....);
    }
}

But still I get some views changes the background color on scrolling which does not match that unique Id.

What is the solution to this problem ?

user13608097
  • 66
  • 2
  • 9

1 Answers1

1

If i understand correctly there are multiple cells with the "unique" color but it shouldn't. This happens because you never reset the background of the layout to the default color.

if(object.uniqueCode() == uniqueCode){
    holder.layout.setBackgroundColor(/*unique color*/);
}
else{
    holder.layout.setBackgroundColor(/*default color*/);
}
K.Kotsi
  • 76
  • 3
  • Yeah it resolved my problem. Thank u so much @K.Kotsi. But can u explain what's going on ? If else has not been given, it should Automatically choose the default color. Right ?. But it doesn't do that ! – user13608097 Jun 11 '20 at 07:10
  • 1
    That's the way the RecyclerView works. Let's say that you want to show 5 cells. Android will use the same 5 views and will only change the data you want to show. It will **not** create new views. OnBindViewHolder is called only when android is changing the data it is about to show at a particular cell. Instead OnCreateViewHolder is called when a new cell is created. Try running some tests to understand how it works also see this stackoverflow [answer](https://stackoverflow.com/a/36043506/6115254) – K.Kotsi Jun 11 '20 at 08:07