Skip to content Skip to sidebar Skip to footer

How To Use Different Layouts For Incoming & Outgoing Chat Messages

I have a design for messages. 2 xml files are responsible for the design: recyclerview_item_incoming.xml recyclerview_item_outgoing.xml It looks like this: Messages are stored in

Solution 1:

The getItemViewType() is the right place for determining the item layout. So you need to move the logic there, so override it in the adapter:

@Override
publicintgetItemViewType(int position) {
    if (getItem(position).getNature().equals("outgoing"))
        return R.layout.recyclerview_item_outgoing;
    elsereturn R.layout.recyclerview_item_incoming;
}

And that being reflected in the viewType parameter of onCreateViewHolder(), so it holds the right layout for the current item. So you'd pass that to the ViewHolder:

@Overridepublic MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return MessageViewHolder.create(parent, viewType);
}

And In ViewHolder set that as your layout:

static MessageViewHolder create(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(viewType, parent, false);
    returnnew MessageViewHolder(view);
}

Post a Comment for "How To Use Different Layouts For Incoming & Outgoing Chat Messages"