倒計時效果實現

倒計時效果實現

1、倒計時工具類的實現

public class CountDownTimerUtils extends CountDownTimer implements View.OnClickListener {
    private static final String TAG = CountDownTimerUtils.class.getSimpleName();
    //普通倒計時
    public static int NORMAL = 1;
    //首頁登陸獲取驗證碼
    public static int VERIFICODE = 2;
    //倒計時類型
    private static int type = NORMAL;
    private TextView mTextView;//用於顯示倒計時數字,也可作爲按鈕使用
    private boolean isCounting=false;
    private IReacquireListener iReacquireListener;

    public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval, int setType) {
        super(millisInFuture, countDownInterval);//倒計時長,回調#onTick方法間隔時間
        type = setType;
        mTextView = textView;
        mTextView.setOnClickListener(this);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        isCounting=true;
        mTextView.setClickable(false);
        int second= (int) (millisUntilFinished / 1000);
        Log.i(TAG, "onTick: second= "+second);
        mTextView.setText(String.format(mTextView.getResources().getString(R.string.unit_second), second + ""));
        //如果設置驗證碼倒計時
        if (type == VERIFICODE){
            mTextView.setBackgroundResource(R.drawable.btn_pressed_background);

            SpannableString spannableString = new SpannableString(mTextView.getText().toString());
            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#F0752B"));
            spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//將倒計時的時間設置爲紅色
            mTextView.setText(spannableString);
        }

        Log.i(TAG, "onTick: isCounting= "+isCounting());
    }

    @Override
    public void onFinish() {
        isCounting = false;
        //如果設置驗證碼倒計時
        if (type == VERIFICODE){
            mTextView.setText(R.string.reacquire_verify_code);
            mTextView.setClickable(true);
            mTextView.setBackgroundResource(R.drawable.btn_background_selector);
        }else if (type == NORMAL){
            mTextView.setText("");
        }
        Log.i(TAG, "onFinish: isCounting= "+isCounting());
    }

    @Override
    public void onClick(View v) {
        iReacquireListener.reacquire();
    }

    //重新獲取驗證碼回調接口
    public interface IReacquireListener{
        void reacquire();
    }

    public void setReacquireListener(IReacquireListener listener){
        iReacquireListener=listener;
    }

    public boolean isCounting(){
        return isCounting;
    }

}

2、在代碼中的使用

CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(tvCounter, 60000, 1000, VERIFICODE);
//開始倒計時
countDownTimerUtils.start();
//結束倒計時
countDownTimerUtils.cancel();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章