Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實作「獲取驗證碼」倒數計時按鈕

編輯:關於 Android 程式設計

功能很單純:點一下按鈕發送驗證碼,然後按鈕進入 60 秒倒數,倒數期間不可再點,結束後恢復。這類互動在註冊、找回密碼頁面幾乎必備。

實作核心只有一個類:CountDownTimer。它幫你處理好計時與主執行緒調度的細節,你只要覆寫兩個方法。

布局

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_getcode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:background="#4DB74A"
        android:text="點我獲取驗證碼" />
</RelativeLayout>

主程式碼

package com.example.countdowntimer;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private TimeCount time;
    private Button btnGetcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        time = new TimeCount(60000, 1000);

        btnGetcode = (Button) findViewById(R.id.btn_getcode);
        btnGetcode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                time.start();
            }
        });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnGetcode.setBackgroundColor(Color.parseColor("#B6B6D8"));
            btnGetcode.setClickable(false);
            btnGetcode.setText(millisUntilFinished / 1000 + " 秒後可重新發送");
        }

        @Override
        public void onFinish() {
            btnGetcode.setText("重新獲取驗證碼");
            btnGetcode.setClickable(true);
            btnGetcode.setBackgroundColor(Color.parseColor("#4EB84A"));
        }
    }
}

兩個建構參數的意義

millisInFuture = 60000:總倒數時間,單位毫秒,60000 就是 60 秒。

countDownInterval = 1000:回呼間隔,1000 表示每秒觸發一次 onTick。這裡剛好等於 1 秒,所以 millisUntilFinished / 1000 直接就是剩餘秒數。

如果間隔設成 500,onTick 每半秒觸發一次,那麼 millisUntilFinished / 1000 會連續出現兩次相同數字,介面文字看起來「卡」了一下——這是調整參數時容易忽略的細節。

兩個回呼的分工

onTick() 在倒數期間週期性呼叫,參數 millisUntilFinished 是剩餘毫秒數。這裡同時做了三件事:改背景色(視覺上表示不可用)、setClickable(false)(真正阻擋點擊)、更新文字。

onFinish() 在倒數歸零時呼叫一次,把按鈕恢復成可點擊狀態與原始樣式。

CountDownTimer 的計時基礎是 SystemClock,且所有回呼都在建立它的執行緒上執行——在 Activity 中建立即在主執行緒,所以可以直接操作 UI,不需要額外的 Handler。

幾個值得修正的問題

setClickable(false) 擋不住所有情況。更嚴謹的做法是同時設 isEnabled,或者在 onClick 裡加一個布林旗標判斷。單靠 setClickable 在部分情境下仍可能觸發。

計時器必須取消,否則洩漏。CountDownTimer 是非同步的,Activity 銷毀後若倒數還在跑,內部持有的 Activity 引用無法釋放。務必在 onDestroy 中收尾:

@Override
protected void onDestroy() {
    if (time != null) {
        time.cancel();
    }
    super.onDestroy();
}

每次點擊都該重新建立計時器。CountDownTimer 的 start() 只能呼叫一次,第二次呼叫會拋「This CountDownTimer is already started」。所以更安全的寫法是在 onClick 裡 new 一個新的計時器,或者先 cancel 再 start。

橫屏旋轉會重置倒數。Activity 重建後倒數狀態遺失。若在意這個體驗,需要透過 onSaveInstanceState 保存剩餘時間,或把計時邏輯移到 ViewModel 中。

驗證碼發送本身要在這裡做。範例只處理了倒數 UI,實際專案還要在 time.start() 之前呼叫後端介面發送簡訊,並處理發送失敗的情況——失敗時應該立刻 cancel 計時器並恢復按鈕,否則使用者要乾等 60 秒。

Kotlin 更簡潔的寫法

如果用 Kotlin,配合物件表達式可以寫得更緊湊,同時用 lifecycleScope 天然解決洩漏問題。核心邏輯不變:倒數期間鎖定按鈕並顯示剩餘秒數,歸零後解鎖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved