Skip to content
Advertisement

Incorrect displaying items in RecyclerView while scrolling

Could you please assist in following issue:

I have incorrect displaying items in my messenger app.

My layout for items:

JavaScript

My layout for dialog activity:

JavaScript

Class DialogActivity

JavaScript

Adapter class

JavaScript

In this place I check user name.

JavaScript

If user name is my name then I set message and visible to holder.messageMyMessage. Else I set message and visible to holder.messageYourMessage. But sometimes message and visible are set to both messages while scrolling or sent new message. . See attached screenshot for details

Advertisement

Answer

Your problem’s here:

JavaScript

You’re only making stuff visible, you’re never hiding the other thing.

So if a specific ViewHolder is used to display one kind of message, it’ll be made visible in onBindViewHolder. The view in that ViewHolder’s layout will be set to VISIBLE.

Then, if you scroll down the list and the same ViewHolder is reused to display the other kind of message, the other message view in the layout will be set to VISIBLE. The other message view hasn’t changed, it’s still in the same state, VISIBLE. So you see them both (depending on how the layout works, one might be covering the other).

When you’re using a RecyclerView, because the ViewHolders are reused (recycled) you need to set them up correctly for each item, clearing all the previous state. So in your case, for each message display, you have to either make it visible or hide it. You can’t do nothing, because that can leave you with old state from the previous item it was displaying, right?

So you need to do this:

JavaScript

This is the number one thing you need to do with a RecyclerView – in onBindViewHolder, always set up everything that can change depending on the item. Assume it has old data or the wrong thing set, and explicitly initialise everything. It’s like a whiteboard – when you start using it you need to clean it, because maybe there’s some old stuff on there

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement