I'm developing chat application and i've already design dummy chat history.But i'm stuck at how to group messages according to it's date and when we scroll it down,date indicator stick at the top position just like whats app. can you just show me the way, how can i achieve that? I've attached some screenshot below to elaborate my question.
Asked
Active
Viewed 7,496 times
2 Answers
12
Put your header in your custom lisview adapter layout and check everytime your current message date and previous message date. If date is same then hide your header otherwise show your header. See below:
holder.tvDate.setText(chatMessage.getDate());
if (position > 0) {
if (chatMessages.get(position).getDate().equalsIgnoreCase(chatMessages.get(position - 1).getDate())) {
holder.header.setVisibility(View.GONE);
} else {
holder.header.setVisibility(View.VISIBLE);
}
} else {
holder.header.setVisibility(View.VISIBLE);
}

Krupa Kakkad
- 857
- 1
- 13
- 28
-
Are you used recyclerview to show the above list? I have used recyclerview but it failed to show the datetime – sejn Apr 19 '21 at 06:49
-
I have used listview at that time. But you can also achieve this in recyclerview. – Krupa Kakkad Apr 19 '21 at 07:22
-
Ihave used recyclerview, but it failed to sho the datetime view. Did u did like this? https://stackoverflow.com/questions/67058427/failed-to-show-the-grouping-date-view-for-the-chat-messages-in-the-recyclerview/67124150#67124150 – sejn Apr 19 '21 at 07:49
0
Simple. Just add a header view to your ListView
TextView textView = new TextView(context);
textView.setText("Hello. I'm a header view");
listView.addHeaderView(textView);
for more details- https://developer.android.com/reference/android/widget/ListView.html#addHeaderView(android.view.View)
Update:
By far the simplest way to do this is to embed the date header view in every item. Then, all you need to do in bindView is compare the previous row's date to this row's date, and hide the date if it's the same. Something like this:
String thisDate = cursor.getString(dateIndex);
String prevDate = null;
// get previous item's date, for comparison
if (cursor.getPosition() > 0 && cursor.moveToPrevious()) {
prevDate = cursor.getString(dateIndex);
cursor.moveToNext();
}
// enable section heading if it's the first one, or
// different from the previous one
if (prevDate == null || !prevDate.equals(thisDate)) {
dateSectionHeaderView.setVisibility(View.VISIBLE);
} else {
dateSectionHeaderView.setVisibility(View.GONE);
}

Sourav Bagchi
- 656
- 7
- 13
-
as you can see in above screenshot , there is more than one header Yesterday , Today and list view contain only one header @saurav – Tejas Pandya Nov 25 '16 at 11:55