如何创建像 whatsapp 这样的第 header 部分列表?

How to create section header listing like whatsapp?

我正在开发聊天应用程序,并且我已经设计了虚拟聊天 history.But 我被困在如何根据日期对消息进行分组以及当我们向下滚动它时,日期指示器会显示在顶部位置就像什么应用程序一样。你能给我指路吗,我怎样才能做到这一点?我在下面附上了一些屏幕截图来详细说明我的问题。

简单。只需将 header 视图添加到您的 ListView

TextView textView = new TextView(context);
textView.setText("Hello. I'm a header view");

listView.addHeaderView(textView);

了解更多详情- https://developer.android.com/reference/android/widget/ListView.html#addHeaderView(android.view.View)

更新:

到目前为止,最简单的方法是在每个项目中嵌入日期 header 视图。然后,您需要在 bindView 中做的就是将上一行的日期与本行的日期进行比较,如果相同则隐藏日期。像这样:

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

将您的 header 放入您的自定义 lisview 适配器布局中,并每次检查您的当前消息日期和之前的消息日期。如果日期相同则隐藏你的 header 否则显示你的 header。见下文:

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