安卓自定义倒计时控件

用途

实现倒计时效果.

效果图

安卓自定义倒计时控件_第1张图片

主要代码

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

使用样例

  1. 布局文件中增加如下内容:

  1. 设置回调
countDownTv.setCallback(object : OnFinishCallback {
    override fun onFinished() {
        Toast.makeText(this@MainActivity, "dddd", Toast.LENGTH_LONG).show()
    }
})

完整源代码

https://gitee.com/cxyzy1/count-down-timer

你可能感兴趣的:(安卓自定义倒计时控件)