How to add dates in recyclerview for a chat?

我只是一个虾纸丫 提交于 2019-12-12 01:38:07

问题


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?


回答1:


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(...);
             ...
         }
    }
}


来源:https://stackoverflow.com/questions/39688047/how-to-add-dates-in-recyclerview-for-a-chat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!