註冊時擷取驗證碼常用的倒計時工具,註冊時驗證碼
//在這個構造方法裡需要傳入三個參數,一個是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);
}
}