安卓自定义倒计时控件
2020-10-29 本文已影响0人
蓝不蓝编程
用途
实现倒计时效果.
效果图
主要代码
class CountDownTextView(context: Context, attrs: AttributeSet? = null) :
AppCompatTextView(context, attrs) {
private var mOnFinishCallback: OnFinishCallback? = null
private var startNum = 10
private var endNum = 1
private val intervalTime = 500 //重绘间隔时间
var currentNum = startNum
init {
background = getCircleDrawable()
text = currentNum.toString()
}
fun setCallback(onFinishCallback: OnFinishCallback) {
mOnFinishCallback = onFinishCallback
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 隔一段时间重绘一次, 动画效果
handler.postDelayed(runnable, intervalTime.toLong())
}
private val runnable = Runnable {
changeText()
invalidate()
}
private fun changeText() {
if (currentNum > endNum) {
currentNum--
} else {
mOnFinishCallback?.onFinished()
visibility = GONE
}
text = currentNum.toString()
}
private fun getCircleDrawable() = GradientDrawable().also {
it.shape = GradientDrawable.OVAL
val strokeWidth = 4 // 边框宽度
val strokeColor = Color.parseColor("#FFD700") //边框颜色
it.setStroke(strokeWidth, strokeColor)
it.setColor(Color.parseColor("#DA70D6"))
}
}
interface OnFinishCallback {
fun onFinished()
}
使用样例
- 布局文件中增加如下内容:
<cn.cxy.countdown.CountDownTextView
android:id="@+id/countDownTv"
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="50sp" />
- 设置回调
countDownTv.setCallback(object : OnFinishCallback {
override fun onFinished() {
Toast.makeText(this@MainActivity, "dddd", Toast.LENGTH_LONG).show()
}
})