美文网首页安卓开发
安卓自定义倒计时控件

安卓自定义倒计时控件

作者: 蓝不蓝编程 | 来源:发表于2020-10-29 10:08 被阅读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()
    }
    

    使用样例

    1. 布局文件中增加如下内容:
    <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" />
    
    1. 设置回调
    countDownTv.setCallback(object : OnFinishCallback {
        override fun onFinished() {
            Toast.makeText(this@MainActivity, "dddd", Toast.LENGTH_LONG).show()
        }
    })
    

    完整源代码

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

    相关文章

      网友评论

        本文标题:安卓自定义倒计时控件

        本文链接:https://www.haomeiwen.com/subject/ywhkvktx.html