Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 控制項倒計時的實作

要做「60 秒後可再送出」這類驗證碼按鈕,用 CountDownTimer 最省事。以下把 Button 封裝進一個自訂類別,讓它自己處理倒數期間的外觀與禁用狀態。

public class CountDownButton extends CountDownTimer {
    public static final int TIME_COUNT_FUTURE = 60000;   // 總時長 60 秒
    public static final int TIME_COUNT_INTERVAL = 1000;  // 每 1 秒回呼一次

    private Context mContext;
    private Button mButton;
    private String mOriginalText;
    private Drawable mOriginalBackground;
    private Drawable mTickBackground;
    private int mOriginalTextColor;

    public CountDownButton() {
        super(TIME_COUNT_FUTURE, TIME_COUNT_INTERVAL);
    }

    public CountDownButton(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    /** 傳入要控制的 Button,並記錄原始外觀以便倒數結束後還原 */
    public void init(Context context, Button button) {
        this.mContext = context;
        this.mButton = button;
        this.mOriginalText = mButton.getText().toString();
        this.mOriginalBackground = mButton.getBackground();
        this.mTickBackground = this.mOriginalBackground;
        this.mOriginalTextColor = mButton.getCurrentTextColor();
    }

    /** 倒數期間想換上的背景,例如灰階樣式 */
    public void setTickDrawable(Drawable tickDrawable) {
        this.mTickBackground = tickDrawable;
    }

    @Override
    public void onFinish() {
        if (mContext != null && mButton != null) {
            mButton.setText(mOriginalText);
            mButton.setTextColor(mOriginalTextColor);
            mButton.setBackgroundDrawable(mOriginalBackground);
            mButton.setClickable(true);
        }
    }

    @Override
    public void onTick(long millisUntilFinished) {
        if (mContext != null && mButton != null) {
            mButton.setClickable(false);
            mButton.setBackgroundDrawable(mTickBackground);
            mButton.setTextColor(mContext.getResources()
                    .getColor(android.R.color.darker_gray));
            mButton.setText(mOriginalText + "(" + millisUntilFinished / 1000 + "')");
        }
    }
}

使用方式

CountDownButton timer = new CountDownButton();
timer.init(this, btnSend);
timer.start();

幾個實務提醒

倒數中把 setClickable(false) 是為了避免使用者連點觸發重複請求,但更嚴謹的做法是同時在 onClick 裡用一個 boolean 旗標把關,因為 setClickable 只攔住 UI 事件,攔不住程式內部的直接呼叫。

其次,CountDownTimer 的計時基準是 SystemClock.elapsedRealtime() 一類的單調時鐘,不受使用者改系統時間影響,這點比用 Timer 加 Date 可靠。但若在倒數途中 Activity 被銷毀,計時也會跟著結束,因此跨頁面(例如旋轉螢幕)要維持倒數,需把剩餘毫秒數存進 savedInstanceState 或 ViewModel 再重建。

最後,getColor(int) 在 API 23 以後已棄用,新專案請改用 ContextCompat.getColor(context, id) 或 getColor(int, Theme);setBackgroundDrawable 亦應改為 setBackground。

Copyright © Linux教程網 All Rights Reserved