美文网首页
验证码倒计时工具类

验证码倒计时工具类

作者: pdog18 | 来源:发表于2017-04-06 16:31 被阅读93次
    class VerifyCodeUtil<T : TextView>(private val textView: T,
                                       private val defaultText: String = "发送验证码",
                                       private var countDown: Int = 60) {
    
        private var running = false
    
        private var runnable: Runnable = Runnable {
            if (!running) {
                return@Runnable
            }
    
            if (countDown-- == 0) {
                finish()
                return@Runnable
            }
    
            updateText()
        }
    
        // 开始倒计时
        fun start() {
            running = true
            textView.isEnabled = false
            startBlock(textView)
            updateText()
        }
    
        @SuppressLint("SetTextI18n")
        private fun updateText() {
            textView.text = "${countDown}s重新获取"
            textView.postDelayed(runnable, 1000L)
        }
    
        // 结束倒计时
        fun finish() {
            running = false
            textView.isEnabled = true
            textView.text = defaultText
            finishBlock(textView)
        }
    
        private var startBlock: (T) -> Unit = {}
        private var finishBlock: (T) -> Unit = {}
    
        fun doOnStart(startBlock: (T) -> Unit) = this.apply {
            this.startBlock = startBlock
        }
    
        fun doOnFinish(finishBlock: (T) -> Unit) = this.apply {
            this.finishBlock = finishBlock
        }
    }
    
    使用
      val verifyCodeUtil = VerifyCodeUtil(tv_get_verify_code)
                    .doOnStart { it.solid = Color.GRAY }
                    .doOnFinish { it.solid = Color.parseColor("#FF5818") }
                    .apply {
                        this.start()    // 启动倒计时
                    }
    
    // 关闭倒计时
    verifyCodeUtil.finish()
    

    相关文章

      网友评论

          本文标题:验证码倒计时工具类

          本文链接:https://www.haomeiwen.com/subject/htyqattx.html