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

註冊驗證碼倒計時工具類:CountDownTimer 實戰封裝

編輯:關於 Android 開發

註冊驗證碼倒計時工具類:CountDownTimer 實戰封裝


在註冊頁面,「獲取驗證碼」按鈕通常需要一個倒計時效果,避免使用者頻繁點擊。本文封裝了一個可重複使用的倒計時工具類,基於 Android 原生的 CountDownTimer 實現,讓按鈕在倒數期間變灰不可點,倒數結束後再恢復可點擊狀態。

在這個構造方法裡需要傳入幾個參數:一個是 Activity,一個是總時間 millisInFuture,一個是每次遞減的時間,最後一個是要顯示倒計時的按鈕。

用法:

TimeLastUtil timeLastUtil = new TimeLastUtil(this, 60000, 1000, btn);
timeLastUtil.start();

工具類:

public class TimeLastUtil extends CountDownTimer {

 private Activity mActivity;
 private TextView btn;// 按鈕

 //在這個構造方法裡需要傳入幾個參數,一個是Activity,一個是總的時間millisInFuture,
 // 一個是countDownInterval,然後就是你在哪個按鈕上做這個,就把這個按鈕傳過來
 public TimeLastUtil(Activity mActivity, long millisInFuture,
 long countDownInterval, TextView btn) {
 super(millisInFuture, countDownInterval);
 this.mActivity = mActivity;
 this.btn = btn;
 }

 @SuppressLint("NewApi")
 @Override
 public void onFinish() {
 btn.setText(R.string.register_regetchecknum);
 btn.setClickable(true);// 重新獲得點擊
 btn.setBackgroundColor(Color.parseColor("#00CCCC"));// 還原背景色
 }

 @Override
 public void onTick(long millisUntilFinished) {
 btn.setClickable(false);// 設置不能點擊
 btn.setText(millisUntilFinished / 1000 + "s後可重新發送");// 設置倒計時時間

 // 設置按鈕為灰色,這時是不能點擊的
 btn.setBackgroundColor(Color.GRAY);
 Spannable span = new SpannableString(btn.getText().toString());// 獲取按鈕的文字
 span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,
 Spannable.SPAN_INCLUSIVE_EXCLUSIVE);// 把倒計時時間顯示為紅色
 btn.setText(span);
 }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved