安卓开发经常遇到获取验证码,实现按钮倒计时的功能
实现起来也很简单,利用系统自带的定时器来实现,下面给出实测代码
调用也很简单
CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(mTextView, 60000, 1000);
在点击这个按钮的时候调用启动就可以了
mTextView.setOnClickListener(v -> {
countDownTimerUtils.start();
});
下面就是封装的类,哪里需要直接调用就可以了
package com.ceq.core.utils.core;
import android.os.CountDownTimer;
import android.widget.TextView;
/**
-
不带记忆功能的倒计时
*/
public class CountDownTimerUtils extends CountDownTimer {/**
- @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 receive
- {@link #onTick(long)} callbacks.
*/
private TextView textView;
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textView = textView;
}@Override
public void onTick(long millisUntilFinished) {
textView.setClickable(false);
textView.setText(“剩余” + millisUntilFinished / 1000 + “s”);
}@Override
public void onFinish() {
textView.setClickable(true);
textView.setText(“获取验证码”);
}
}