Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a date like Whatsapp on scrolling ListView

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

enter image description here

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.

enter image description here

like image 587
Manish Gupta Avatar asked Sep 08 '16 17:09

Manish Gupta


1 Answers

enter image description here

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
            }

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()

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
        }

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.

like image 131
Kishan Solanki Avatar answered Nov 04 '22 05:11

Kishan Solanki