前端时间公司项目需要使用倒计时。我在网上搜了一阵子,发现网上大部分都是 启动一个子线程 ,然后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: 第一次写东西,不喜勿喷。欢迎交流
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/895777.html