現在基本上每個APP註冊時都有短信驗證碼,這就有倒計時的需求了,本來以爲很難,在網上搜了一下很多代碼,直接拿來用,真是soeasy!
話不多說,上代碼:
btn_time.setOnClickListener(this);//獲取驗證碼按鈕
case R.id.btn_time:
CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(btn_time, 60000, 1000);
mCountDownTimerUtils.start();
break;
重要的工具類:
public class CountDownTimerUtils extends CountDownTimer {
private TextView mTextView;
/**
* @param textView The TextView
*
*
* @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 receiver
* {@link #onTick(long)} callbacks.
*/
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.mTextView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
mTextView.setClickable(false); //設置不可點擊
mTextView.setText(millisUntilFinished / 1000 + "秒後可重新發送"); //設置倒計時時間
mTextView.setBackgroundResource(R.drawable.bg_identify_code_press); //設置按鈕爲灰色,這時是不能點擊的
/**
* 超鏈接 URLSpan
* 文字背景顏色 BackgroundColorSpan
* 文字顏色 ForegroundColorSpan
* 字體大小 AbsoluteSizeSpan
* 粗體、斜體 StyleSpan
* 刪除線 StrikethroughSpan
* 下劃線 UnderlineSpan
* 圖片 ImageSpan
* http://blog.csdn.net/ah200614435/article/details/7914459
*/
SpannableString spannableString = new SpannableString(mTextView.getText().toString()); //獲取按鈕上的文字
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
/**
* public void setSpan(Object what, int start, int end, int flags) {
* 主要是start跟end,start是起始位置,無論中英文,都算一個。
* 從0開始計算起。end是結束位置,所以處理的文字,包含開始位置,但不包含結束位置。
*/
spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//將倒計時的時間設置爲紅色
mTextView.setText(spannableString);
}
@Override
public void onFinish() {
mTextView.setText("重新獲取驗證碼");
mTextView.setClickable(true);//重新獲得點擊
mTextView.setBackgroundResource(R.drawable.bg_identify_code_normal); //還原背景色
}
}
效果圖:
好了,就是這麼簡單完成了。。。