Android 自定义View之倒计时
概述
代码实现
Kotlin代码:
class CountdownView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr), Runnable {
private var totalSecond = 10
private var currentSecond = 0
private var TIMING_FINISHED = "发送验证码"
private val TIMING_TEXT = "已发送(%d)"
init {
text = TIMING_FINISHED
gravity = Gravity.CENTER
minWidth = 80.dp
textSize = 13F
setPadding(10.dp)
setTextColor(Color.parseColor("#FFFFFF"))
background = ContextCompat.getDrawable(context, R.drawable.selector_countdown)
}
/**
* 开始倒计时
*/
fun start() {
isEnabled = false
currentSecond = totalSecond
post(this)
}
/**
* 结束倒计时
*/
fun cancel() {
currentSecond = 0
text = TIMING_FINISHED
isEnabled = true
}
override fun run() {
if (currentSecond == 0) {
cancel()
return
}
currentSecond--
text = String.format(TIMING_TEXT, currentSecond)
postDelayed(this, 1000)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
removeCallbacks(this)
}
}
selector_countdown.xml:
<?xml version="1.0" encoding="utf-8"?><!-- 默认获取验证码按钮样式 -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="#BBBBBB" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="#FFB716" />
</shape>
</item>
</selector>
使用:
countdownView.start()