问题
How can I show dates in an app when I scroll the ListView like in WhatsApp?
See the below image for clarity:
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.
回答1:
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.
回答2:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String strDate = sdf.format(cal.getTime());
today = new String[user.length()];
yesterday = new String[user.length()];
earlier = new String[user.length()];
int t_counter = 0;
int y_counter = 0;
int e_counter = 0;
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
post = c.getString(TAG_TEXT).toString();
date = c.getString(TAG_DATE).toString();
time = c.getString(TAG_TIME).toString();
if (strDate.equals(c.getString(TAG_DATE.toString()))) {
if (t_counter == 0) {
TextView tv = getTextView(lp, "Today");
myLayout.addView(tv);
t_counter = t_counter + 1;
}
View msgView = generateChatView(post, time);
myLayout.addView(msgView);
}
try {
temp = sdf.parse(c.getString(TAG_DATE.toString()));
c_date = sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
if (c_date.getTime() - temp.getTime() == 86400000) {
if (y_counter == 0) {
TextView tv = getTextView(lp, "Yesterday");
myLayout.addView(tv);
;
y_counter = y_counter + 1;
}
View msgView = generateChatView(post, time);
myLayout.addView(msgView);
}
if (c_date.getTime() - temp.getTime() > 86400000) {
if (e_counter == 0) {
TextView tv = getTextView(lp, "Earlier");
myLayout.addView(tv);
e_counter = e_counter + 1;
}
View msgView = generateChatView(post, time);
myLayout.addView(msgView);
}
}
来源:https://stackoverflow.com/questions/39397127/how-to-display-a-date-like-whatsapp-on-scrolling-listview