1. 程式人生 > >給大家分享一個在Android中獲取驗證碼的倒數計時器,已經封裝好了,直接引用就行。

給大家分享一個在Android中獲取驗證碼的倒數計時器,已經封裝好了,直接引用就行。

獲取簡訊驗證碼後,倒數一分鐘,重新獲取



package com.example.tsx.mytest;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.Button;


public class TimeCountUtil extends CountDownTimer {
    private Activity mActivity;
    private Button btn;//按鈕


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




    @SuppressLint("NewApi")
    @Override
    public void onTick(long millisUntilFinished) {
        btn.setClickable(false);//設定不能點選
        btn.setText(millisUntilFinished / 1000 + "s");//設定倒計時時間


        //設定按鈕為灰色,這時是不能點選的
        btn.setBackground(mActivity.getResources().getDrawable(R.drawable.send_code_backg));
        Spannable span = new SpannableString(btn.getText().toString());//獲取按鈕的文字
        span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//講倒計時時間顯示為紅色
        btn.setText(span);


    }




    @SuppressLint("NewApi")
    @Override
    public void onFinish() {
        btn.setText("重新獲取");
        btn.setClickable(true);//重新獲得點選
        btn.setBackground(mActivity.getResources().getDrawable(R.drawable.codebackg));//還原背景色


    }




}