0

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?

CantThinkOfAnything
  • 1,129
  • 1
  • 15
  • 40

1 Answers1

5

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(...);
             ...
         }
    }
}
Mirjalol Bahodirov
  • 2,053
  • 1
  • 11
  • 16
  • yeah, i guess this is the way to go indeed. I just thought that maybe i could handle it differently. Making the date-time into a real list item will add some complexity into my chat listbut i guess its unavoidable. – CantThinkOfAnything Sep 25 '16 at 14:52
  • You are right about complexity of date-times. That's why they are will be generated at the backend part :-) – Mirjalol Bahodirov Sep 25 '16 at 14:56
  • 1
    its not necesarily about the date times, its just that my list has over 10 item types and quite some complex logic that uses item position to decide which item should have which kind of information. Adding more types only for showing date will ask me to expand my current logic to incorporate the date stuff :p – CantThinkOfAnything Sep 25 '16 at 15:01