Stubborn
Stubborn

Reputation: 968

Recyclerview: custom style for each item not updating on scroll

I want to assign a custom text color for some of the items in a recyclerview, based on a field of the object they represent. In order to do that, in onBindViewHolder, I put the following code:

if(elements.get(position).colored) {
   holder.element_title.setTextColor(RED);
}

However, when I scroll, it seems like the text color remains "attached" to the element's view, which is then used to display other items. Therefore, some items appear red while they should not. To fix this, in the activity which contains the recyclerview, I tried adding the following code:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
       super.onScrollStateChanged(recyclerView, newState);
       myAdapter.notifyDataSetChanged();
    }
});

This, albeit far from being optimal, seems to solve the issue when I scroll down, but not when I scroll up.

How can I fix this problem?

Upvotes: 0

Views: 69

Answers (2)

oziomajnr
oziomajnr

Reputation: 1751

This is happening because you are only setting the color to red without resetting the color if it's not colored. The view holders are being reused for different items so if you do not reset it would not change. So you should do this

if(elements.get(position).colored) {
   holder.element_title.setTextColor(RED);
} else {
holder.element_title.setTextColor(DEFAULT_COLOR);
}

Upvotes: 1

Parth
Parth

Reputation: 791

RecyclerView works that way. It recycle your view once they disappeared from your screen. To sum up edit your code this way.

if(elements.get(position).colored) {
   holder.element_title.setTextColor(RED);
}else{
   holder.element_title.setTextColor(OTHER THAN RED);
}

and remove addOnScrollListener it's unnecessary.

Upvotes: 2

Related Questions