最简单的时间轴实现

时间轴在一些小清新的app还是能带来不错的效果,我这里只是简单的实现了一下。由于代码没有做什么封装,都是还是比较简单已读,适合初学者。
先看看效果图吧。
这里写图片描述
在使用时需要传入的数据,只需要传入item的时间,然后就可以根据时间,自动判断是今天、昨天、刚刚、5分钟、10分钟等等。item的其他数据,读者可以自由添加。这里主要的代码有对头部添加和时间的判断。
自动头部添加代码如下:

   private List<PoliceOfThingBean> sorting(List<PoliceOfThingBean> data) {
        long mTime = 0;
        int month = 0; //上一条的月份
        int day = 0;
        //动态添加时间标题样式
        for (int i = 0; i < data.size(); i++) {
            long time = data.get(i).getTime();
            mTime = i == 0 ? time : mTime;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(time));
            //判断是否是同一天
            int cuDay = calendar.get(Calendar.DAY_OF_MONTH);
            int cuMonth = calendar.get(Calendar.MONTH);
            if (day != cuDay || cuMonth != month) {
                //如果不是同一天,则添加标题样式
                PoliceOfThingBean bean = new PoliceOfThingBean();
                bean.setMode(0);
                bean.setTime(time);
                data.add(i,bean);
            }
            month = cuMonth;
            day =cuDay;
        }
        return data;
    }

对时间的判断,我这里单独提出到一个工具类中,这样方便应用中其他地方如果有相同的时间显示需求是,可以快速使用。部分代码如下:

 public static String getTime(long time) {
        long diff = System.currentTimeMillis() - time;
        int judgment = (int) (diff / 60000);//距离现在多少分钟
        String result = "";
        if (judgment < 5) {
            result = "刚刚";
        } else if (judgment < 10) {
            result = "5分钟前";
        } else if (judgment < 30) {
            result = "10分钟前";
        } else if (judgment < 60) {
            result = "30分钟前";
        } else if (judgment < 100) {
            result = "1小时前";
        } else {
            //限时具体时间
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); // 24小时制
            result = sdf.format(new Date(time));
        }
        return result;
    }
 public static String getDay(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 24小时制
        String old = sdf.format(new Date(time));
        String month = old.substring(5, 7);
        String day = old.substring(8, 10);

        Date d = new Date();
        String str = sdf.format(d);
        @SuppressWarnings("unused")
        String nowmonth = str.substring(5, 7);
        String nowday = str.substring(8, 10);
        String result = null;

        int temp = Integer.parseInt(nowday) - Integer.parseInt(day);
        switch (temp) {
            case 0:
                result = "今天";
                break;
            case 1:
                result = "昨天";
                break;
            case 2:
                result = "前天";
                break;
            default:
                result = "以前";
                break;
        }
        return result;
    }

有兴趣的读者可以下载源码,下载地址

发布了36 篇原创文章 · 获赞 6 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章