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 time
But goes out of sync as i scroll though or send a new message
What could be the reason for this? I have tried updating the gravity inside onViewAttachedToWindow
and onViewRecycled
methods too.
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