最簡單的時間軸實現

時間軸在一些小清新的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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章