如何在滚动ListView时显示类似Whatsapp的日期

问题描述:

当我像WhatsApp一样滚动ListView时,如何在应用程序中显示日期?
为了清楚起见,请参见下图:

How can I show dates in an app when I scroll the ListView like in WhatsApp?
See the below image for clarity:

当我滚动ListView时,日期将显示在列表上方.
如果您仍然不明白我的问题,请打开您的WhatsApp,然后转到任何组&开始滚动:您会看到显示较早文本的日期.

When I scroll the ListView, the date gets displayed over the list.
If you still did not understand my question please open your WhatsApp, go to any group & start scrolling: you will see the date getting displayed for older texts.

要显示此屏幕截图的日期,您可以使用

To show date like this screenshot, you can use

val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
if (getDateFromFirebaseTime(messageArrayList[firstVisiblePosition].timestamp.toString().toLong()).isNotEmpty()) {
                tvDay.visibility = View.VISIBLE
                tvDay.text = getDateFromFirebaseTime(messageArrayList[firstVisiblePosition].timestamp.toString().toLong())
            } else {
                tvDay.visibility = View.GONE
            }

我在这里所做的是获取RecyclerView列表中第一个可见项的索引,然后从该索引中获取消息的时间戳,并使用getDateFromFirebaseTime()函数将其显示在 TextView tvDay 中.

What I did here is get the index of first visible item of RecyclerView list, then from that index I get the timestamp of the message and show it in the TextView tvDay using the function getDateFromFirebaseTime()

在ScrollListener的RecyclerView的this方法中添加了上面的代码

Above code is added in ScrollListener's this method of RecyclerView

override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            Log.d("scroll", "scrolling")
            //added here
        }

注意:此处在RecyclerView可用的XML中添加了tvDay. RecyclerViewtvDayRelativeLayouttvDay的同一子代,设置为android:layout_centerHorizontal="true"以便将其保持在顶部居中.

Note: Here tvDay is added in the XML where RecyclerView is available. RecyclerView and tvDay are same child of RelativeLayout and tvDay set as android:layout_centerHorizontal="true" to keep it in top center.