当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 自定义计时器

Android 自定义计时器

2020年07月23日  | 移动技术网移动技术  | 我要评论

前端时间公司项目需要使用倒计时。我在网上搜了一阵子,发现网上大部分都是 启动一个子线程 ,然后TextView 显示。 这种方式引起的两个问题:

1.  子线程写在外面,导致代码有点乱。

2.  倒计时如果在adapter中,实现起来比较麻烦。

刚好我们的倒计时是在adapter中。最后,我通过自定义view,继承 TextView,使用  CountDownTimer 。 把倒计时放在view中。外部调用只需要传入总时长就好了。下面是代码部分(使用的是kotlin)

class MyCountDownTimer : TextView {

    private var countTime = 0L
    private var countDownTimer: MyCountDownTimer? = null

    private var mContext: Context? = context

    constructor (context: Context?) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        mContext = context
    }

    //设置数据
    fun setTime(time: Int) {
        if (time <= 0) {
            return
        }
        this.countTime = time * 1000L

        if (countDownTimer != null) {
            stopTimer()
        }
        startTimer()

    }

    //计时器
    private inner class MyCountDownTimer(totleTime: Long, durTime: Long) : CountDownTimer(totleTime, durTime) {
        override fun onFinish() {
            stopTimer()
        }

        override fun onTick(millisUntilFinished: Long) {
            var timeStr = getTimeByLong(millisUntilFinished / 1000)
            Log.i("111", timeStr)
            text = timeStr
        }

    }

    // hh:mm:ss
    var hour = 60 * 60
    var minute = 60
    fun getTimeByLong(time: Long): String {
        var timeStr = "00:00:00"
        if(time > 0){
            val h = time / hour
            val m = time % hour / minute
            val s = time % minute

            timeStr = String.format("%02d:%02d:%02d",h,m,s)
        }

        return  timeStr
    }


    private fun startTimer() {
        countDownTimer = MyCountDownTimer(countTime, 1000)
        countDownTimer!!.start()
    }

    private fun stopTimer() {
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
            countDownTimer = null
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopTimer()
    }
}

考虑到很多软件的倒计时有背景色之类的,可以用  BackgroundColorSpan  将字符串进行处理后再展示。具体的根据实际需要进行修改

PS: 第一次写东西,不喜勿喷。欢迎交流


 

 

本文地址:https://blog.csdn.net/LoadHappy/article/details/107457133

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网