android - 在回收者 View 中检测上一个项目

标签 android android-recyclerview

我有一个名为(消息)的模型类。在回收器 View 适配器的绑定(bind) View 持有者方法中,我这样做是为了从(消息)类中提取(时间)字符串:

@override
public void onBindViewHolder(final ViewHodler view holder, int position){

  //here I extract the time value from (messages) class

  messages mess=messageslist.get(position);

  //I store it in a long variable called time

  long time= mess.getTime();


 }

到这里为止,我只是在回收站 View 中获取每个项目的时间值。但我还想获取上一项的时间并将其与下一项进行比较。

换句话说,我试图找到 recyclerview 中每 2 个项目之间的时间差。

感谢您的帮助。

编辑

好的,我想做的是在两个项目之间的日期差异达到或超过 1 天时显示或隐藏日期 View 。如果我按照下面的答案去做,我不会得到任何结果......像这样

    //the time of the item
    long time= mess.getTime();

     //the time of the previous item according to the answers below

    long pre_time=messageslist.get(position-1).getTime();


     //now I compare the difference 


      if(time - pre_time >= 24*3600*1000){ 

         //show date
       }else{
         //hide date
        }

但确实有效。

最佳答案

根据更新的问题编辑了答案

您应该将时间毫秒转换为 DAY_OF_MONTH 并检查当前项的日期是否大于前一项的日期。

Calendar calendar = Calendar.getInstance();

Messages mess = messagesList.get(position);
calendar.setTimeInMillis(mess.getTime());
int date = calendar.get(Calendar.DAY_OF_MONTH);

if (position > 0) {
    Messages previousMessage = messagesList.get(position - 1);
    if (previousMessage != null) {
        calendar.setTimeInMillis(previousMessage.getTime());
        int prevDate = calendar.get(Calendar.DAY_OF_MONTH);

        if (date > prevDate) {
            // This is a different day than the previous message, so show the Date
        } else {
            // Same day, so hide the Date
        }

    }
} else {
    // This is the first message, so show the date
}

关于android - 在回收者 View 中检测上一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241544/

相关文章:

android - 两个嵌套 RecyclerView 的滚动行为

android - 在 RecyclerView 中为 pre-Lollipop 绘制着色

android - Vuforia Android SDK 解释示例?

android - android 手机可以充当 usb hid 鼠标吗?

android - RecyclerView中notifyDataSetChanged时如何使指定项不更新

android - 当回收者想要回收一个适配器时调用哪个 Recycler Adapter 方法

Android I2C 读/写速度

java - 已停止申请! GOOGLE API V2 - map

android - 将带有 Javascript 数组的对象附加到 QML ListModel 会导致 SEGFAULT

android - Glide和recyclerview,内存太大