Kotlin中实现简单的倒计时按钮

在kotlin中实现最简单的有倒计时功能的按钮,诸如注册时需要点击获取验证码,点击后直接变成倒计时状态。

/**
 * 创建时间: 2018/12/26 0026
 * 创建人:ldm
 * 功能描述:
 */
class CountdownButton(mContext: Context, attrSet: AttributeSet) : Button(mContext, attrSet) {
    private val mHandler: Handler = Handler();
    private var mCountTime = 60


    init {
        this.text = "点击获取验证码"
    }

    /*
           倒计时,并处理点击事件
        */
    fun sendVerifyCode() {
        mHandler.postDelayed(countDown, 0)
    }

    /*
        倒计时
     */
    private val countDown = object : Runnable {
        override fun run() {
            this@CountdownButton.text = mCountTime.toString() + "s "           this@CountdownButton.setBackgroundColor(resources.getColor(R.color.disable))       this@CountdownButton.setTextColor(resources.getColor(R.color.white))
            this@CountdownButton.isEnabled = false

            if (mCountTime > 0) {
                mHandler.postDelayed(this, 1000)
            } else {
                resetCounter()
            }
            mCountTime--
        }
    }

    fun removeRunable() {
        mHandler.removeCallbacks(countDown)
    }

    //重置按钮状态
    fun resetCounter(vararg text: String) {
        this.isEnabled = true
        if (text.isNotEmpty() && "" != text[0]) {
            this.text = text[0]
        } else {
            this.text = "点击获取验证码"
        }
        this.setBackgroundColor(resources.getColor(R.color.transparent))
        this.setTextColor(resources.getColor(R.color.blue))
        mCountTime = 60
    }
}

在Activity中使用,直接放入到布局中,在代码中实现点击事件即可:
布局文件:

    <com.ldm.kotlin.view.CountdownButton
        android:id="@+id/countdownBtn"
        android:layout_width="150dp"
        android:layout_height="60dp"
        android:gravity="center"
        android:text="点击获取验证码" />

Activity中实现点击事件

 countdownBtn = findViewById(R.id.countdownBtn) as CountdownButton;
        countdownBtn!!.setOnClickListener {
            countdownBtn!!.sendVerifyCode()
        }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值