驗證碼倒計時

package com.sfy.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.TextView

class CountdownTextView : TextView, Runnable {
    private var mTotalTime = 60 // 倒計時秒數
    private val TIME_UNIT = "s" // 秒數單位文本

    private var mCurrentTime: Int = 0 // 當前秒數
    private var mRecordText: CharSequence? = null // 記錄原有的文本
    private var mAfterText: CharSequence? = null// 秒數結束需要展示的文本
    private var mFlag: Boolean = false // 標記是否重置了倒計控件


    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet, 0)

    constructor(context: Context,attributeSet: AttributeSet,defStyle: Int):super(context, attributeSet, defStyle){
        val ta = getContext().obtainStyledAttributes(attributeSet, R.styleable.CountdownViewText)
        mAfterText = if (ta.hasValue(R.styleable.CountdownViewText_afterTipText)) ta.getString(R.styleable.CountdownViewText_afterTipText) else "重新獲取"
    }

    /**
     * 設置倒計時總秒數
     */
    fun setTotalTime(totalTime: Int) {
        this.mTotalTime = totalTime
    }

    /**
     * 重置倒計時控件
     */
    fun resetState() {
        mFlag = true
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        //設置點擊的屬性
        isClickable = true
    }

    override fun onDetachedFromWindow() {
        // 移除延遲任務,避免內存泄露
        removeCallbacks(this)
        super.onDetachedFromWindow()
    }

    override fun performClick(): Boolean {
        val click = super.performClick()
        mRecordText = text
        isEnabled = false
        mCurrentTime = mTotalTime
        post(this)
        return click
    }

    override fun run() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        if (mCurrentTime == 0 || mFlag) {
            text = mAfterText
            //            setText(mRecordText);
            isEnabled = true
            mFlag = false
        } else {
            mCurrentTime--
            text = mCurrentTime.toString() + TIME_UNIT + mAfterText
            postDelayed(this, 1000)
        }
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章