Search code examples
androidandroid-recyclerviewcardview

RecyclerView goes out of Sync


I have created a firebase chat. It uses a RecyclerView with CardViews to show the messages. I'm changing the CardView Gravity inside the OnBindViewHolder method of RecyclerView.Adapter, so the senders messages will be on one side and others in other side(WhatsApp). Here is my code,

public void onBindViewHolder(ViewHolder holder, int position) {
        
        final MessageItem messageItem = messageItems.get(position);
        holder.name.setText(messageItem.getSenderName());
        holder.message.setText(messageItem.getMessage());
        
        if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
            holder.linearLayout.setGravity(Gravity.RIGHT);
        }

    }

This works fine when loading the messages for the first timeenter image description here

But goes out of sync as i scroll though or send a new message enter image description here

What could be the reason for this? I have tried updating the gravity inside onViewAttachedToWindow and onViewRecycled methods too.


Solution

  • Try to change this code

    if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
        holder.linearLayout.setGravity(Gravity.RIGHT);
    }else{
        holder.linearLayout.setGravity(Gravity.LEFT);
    }
    

    You need a to set a left gravity in else because recyclerview recycled view when you scroll