在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()
}