一个自定义倒计时button

这是一个倒计时功能的button。

使用的时候,btn对象直接调用start,cancel方法就可以实现开始计时,取消计时

public class CountdownButton extends android.support.v7.widget.AppCompatButton {

    private final int able = R.drawable.plat_condition_btn_able;
    private Stopwatch stopwatch = null;
    private int countTime = 60;

    public CountdownButton(Context context) {
        this(context, null);
    }

    public CountdownButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountdownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setText(" 点击获取验证码 ");
        resetWatch();
        setEnabled(true);
    }

    @Override
    public void setEnabled(boolean enabled) {
        setBackground(enabled);
        super.setEnabled(enabled);
    }

    private void setBackground(boolean enabled) {
        if (enabled) {
            setTextColor(Color.WHITE);
            setBackgroundResource(able);
        } else {
            setTextColor(0xFFa29395);
            setBackground(null);
        }
    }

    public void start() {
        setEnabled(false);
        stopwatch.cancel();
        stopwatch.start();
    }

    public void cancel() {
        setEnabled(true);
        stopwatch.cancel();
        setText(" 重新获取验证码 ");
        resetWatch();
    }

    private void resetWatch(){
        stopwatch = new Stopwatch(countTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                setText(" " + (millisUntilFinished / 1000 + ((millisUntilFinished % 1000 > 500) ? 1 : 0) + "s后重新发送 "));
            }

            @Override
            public void onFinish() {
                setText(" 重新获取验证码 ");
                setEnabled(true);
            }
        };
    }
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        cancel();
    }
}

计时器stopwatch:

public abstract class Stopwatch{
    private static final String TAG = "Stopwatch";
    /**
     * Millis since epoch when alarm should stop.
     */
    private final long mMillisInFuture;

    /**
     * The interval in millis that the user receives callbacks
     */
    private final long mCountdownInterval;

    private long mStopTimeInFuture;

    /**
     * boolean representing if the timer was cancelled
     */
    private boolean mCancelled = false;

    /**
     * @param millisInFuture The number of millis in the future from the call
     *   to {@link #start()} until the countdown is done and {@link #onFinish()}
     *   is called.
     * @param countDownInterval The interval along the way to receive
     *   {@link #onTick(long)} callbacks.
     */
    public Stopwatch(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }
    /**
     * Cancel the countdown.
     */
    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
    }

    /**
     * Start the countdown.
     */
    public synchronized final Stopwatch start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }


    /**
     * Callback fired on regular interval.
     * @param millisUntilFinished The amount of time until finished.
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * Callback fired when the time is up.
     */
    public abstract void onFinish();


    private static final int MSG = 1;


    // handles counting down
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized (Stopwatch.this) {
                if (mCancelled) {
                    return;
                }
                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
                Log.d(TAG, "Handler"+millisLeft);
                if (millisLeft <= 0) {
                    onFinish();
                } else if (millisLeft < mCountdownInterval) {
                    if(mMillisInFuture%mCountdownInterval==0)
                        onTick(millisLeft);
                    sendMessageDelayed(obtainMessage(MSG), millisLeft);
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    // take into account user's onTick taking time to execute
                    long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

                    // special case: user's onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0) delay += mCountdownInterval;
                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

猜你喜欢

转载自blog.csdn.net/hpp_1225/article/details/84976294