android Chronometer控件使用大全

1、序言

Chronometer 是android 官方提供的計時器、可實現正/倒計時、格式固定:00:00:00;

2、使用

如圖xml 

xml 簡化寫法如下:

<Chronometer
                android:id="@+id/tvEndTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

3、發起倒計時

 tvEndTime.run {
            //格式化-> 距結束00:00:00
            format = "距結束%s"
            //設置倒計時時間 countDownTimeMill -》自定義 單位毫秒
            base = countDownTimeMill + SystemClock.elapsedRealtime()
            //是否為倒計時、
            isCountDown = true
            //倒計時監聽 每隔一秒
            setOnChronometerTickListener {
                //倒計時結束
                if (SystemClock.elapsedRealtime() - it.base >= 0) {
                    it.stop()
                    return@setOnChronometerTickListener
                    // TODO: 2021/9/16 處理業務邏輯 
                }
            }
        }

4、自定義格式化

 tvEndTime.run {
            //格式化-> 距結束00:00:00
            format = "距結束%s"
            //設置倒計時時間
            base = countDownTimeMill + SystemClock.elapsedRealtime()
            //是否為倒計時、
            isCountDown = true
            //倒計時監聽 每隔一秒
            setOnChronometerTickListener {
                //倒計時結束
                if (SystemClock.elapsedRealtime() - it.base >= 0) {
                    it.stop()
                    return@setOnChronometerTickListener
                   //自定義日期格式 如 1天 23:02:56
                it.text = TimeUtils.formatSecondByMill(86400 * 1000)
                }
            }
        }

工具類:

object TimeUtils {
    /**
     * 發送消息日期格式
     *
     * @param msgTimeMillis
     * @return
     */
    fun getMsgFormatTime(msgTimeMillis: Long): String? {
        val nowTime = Date()
        val msgTime = Date(msgTimeMillis)
        val days = differentDays(msgTime, nowTime)
        // 早上、下午、晚上 1:40
        val hourOfDay = DateUtils.getHour(msgTime)
        val whens: String = when {
            hourOfDay >= 18 -> { //18-24
                "晚上"
            }
            hourOfDay >= 13 -> { //13-18
                "下午"
            }
            hourOfDay >= 11 -> { //11-13
                "中午"
            }
            hourOfDay >= 5 -> { //5-11
                "早上"
            }
            else -> { //0-5
                "凌晨"
            }
        }
        return if (days < 1) {
            whens + " " + DateUtils.format(msgTime, "HH:mm")
        } else {
            // 昨天
            //            return DateUtils.format(new Date(msgTimeMillis), "yyyy年MM月dd日 ") + when + DateUtils.format(new Date(msgTimeMillis), " HH:mm");
            DateUtils.format(Date(msgTimeMillis), "yyyy年MM月dd日 ")
        }
    }
 
    /**
     * date2比date1多的天數
     * @param date1
     * @param date2
     * @return
     */
    private fun differentDays(msgTime: Date, nowTime: Date): Int {
        val cal1 = Calendar.getInstance()
        cal1.time = msgTime
        val cal2 = Calendar.getInstance()
        cal2.time = nowTime
        val day1 = cal1[Calendar.DAY_OF_YEAR]
        val day2 = cal2[Calendar.DAY_OF_YEAR]
        val year1 = cal1[Calendar.YEAR]
        val year2 = cal2[Calendar.YEAR]
        return if (year1 != year2) //同一年
        {
            var timeDistance = 0
            for (i in year1 until year2) {
                timeDistance += if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) //閏年
                {
                    366
                } else  //不是閏年
                {
                    365
                }
            }
            timeDistance + (day2 - day1)
        } else  //不同年
        {
            day2 - day1
        }
    }
 
    /**
     * 格式化秒數
     * des:%02d 長度不夠2位的時前面補0
     */
    fun formatSeconds(seconds: Long): String? {
        return when {
            seconds <= 0 -> {
                "00:00"
            }
            seconds < 60 -> {
                String.format(Locale.getDefault(), "00:%02d", seconds % 60)
            }
            seconds < 3600 -> {
                String.format(Locale.getDefault(), "%02d:%02d", seconds / 60, seconds % 60)
            }
            else -> {
                String.format(
                    Locale.getDefault(),
                    "%02d:%02d:%02d",
                    seconds / 3600,
                    seconds % 3600 / 60,
                    seconds % 60
                )
            }
        }
    }
 
    fun formatSecond(seconds: Long): String? {
        return when {
            seconds <= 0 -> {
                "0分"
            }
            seconds < 60 -> {
                String.format(Locale.getDefault(), "%02d秒", seconds % 60)
            }
            seconds < 3600 -> {
                String.format(Locale.getDefault(), "%02d分%02d秒", seconds / 60, seconds % 60)
            }
            else -> {
                String.format(
                    Locale.getDefault(),
                    "%02d時%02d分",
                    seconds / 3600,
                    seconds % 3600 / 60,
                )
            }
        }
    }
 
    /**
     * 格式化日期 eg 天 時:分:秒  00:00:00
     * @param dayUnit 單位 默認不寫
     */
    fun formatSecondByMill(millTime: Long, dayUnit: String = "天"): String? {
        //小於一天、單位毫秒
        return if (millTime <= 86400 * 1000) {
            formatSeconds(millTime / 1000)
        } else {
            val oneDayMill = 86400 * 1000
            val day = millTime / oneDayMill
            val lastOneDayMills = millTime - day * oneDayMill
            "$day$dayUnit ${formatSeconds(lastOneDayMills / 1000)}"
        }
    }
 
}

註意:別再format上做文章、因為沒用!!!

到此這篇關於android Chronometer控件簡單使用的文章就介紹到這瞭,更多相關android Chronometer控件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: