CantThinkOfAnything CantThinkOfAnything - 2 months ago 17
Java Question

How to add dates in recyclerview for a chat?

Im trying to figure out what the way to go would be in order to create date-list-items for in a chat that show from which date the messages belong to.

The list would look like this:

--- 1 week ago ---
msg
msg
msg
msg
msg
----- today -----
msg
msg
msg
msg


One way i can do it is by creating date time list items and then using some logic to decide on which position a date-time-list-item should go.

I was thinking that it may be possible to create a custom list divider for showing the date but i am not sure if this is possible.

How would you guys handle this?

Answer

You know that RecyclerView has multiple view types. It means that you can draw predefined rows as need.

In chat example, exact dates and messages data will be populated at the server side. You need to draw just ready information (maybe json).

I hope that this suggestion may save your time.

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    class ViewHolder0 extends RecyclerView.ViewHolder {
        ...
    }

    class ViewHolder2 extends RecyclerView.ViewHolder {
        ...
    }

    @Override
    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be contiguous
        return position % 2 * 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         switch (viewType) {
             case 0: return new ViewHolder0(...);
             case 2: return new ViewHolder2(...);
             ...
         }
    }
}
Comments