如何在WhatsApp中滚动ListView时如何在应用中显示日期?
为清晰起见,请参见下图:
当我滚动ListView时,日期显示在列表上 如果你仍然不明白我的问题,请打开你的WhatsApp,去任何一个组&开始滚动:您将看到旧文本显示的日期。
答案 0 :(得分:0)
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);
}
}
答案 1 :(得分:0)
要显示此屏幕截图的日期,可以使用
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列表中第一个可见项的索引,然后从该索引中获取消息的时间戳,并使用函数{{1将其显示在 TextView tvDay }}
在ScrollListener的RecyclerView的this方法中添加了上面的代码
getDateFromFirebaseTime()
注意:在override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
Log.d("scroll", "scrolling")
//added here
}
可用的XML中添加了tvDay
。 RecyclerView
和RecyclerView
是tvDay
和RelativeLayout
的子元素,它们被设置为tvDay
,以使其居中。