可用于短信发送倒计时,请求倒计时等各个地方,使用方便,与组件解耦。
- import android.os.CountDownTimer;
- import android.view.View;
- /**
- * 倒计时计时工具
- * @author wjh 2021-01-29
- *
- * 当Activity/Fragment销毁的时候记得 调用CountDownTimerUtils.cancle
- * Fragment在onDestoryView时调用 视图被移除时(reason:CountDownTimerUtils调用可能会涉及Ui的改变)
- *
- */
-
- public class CountDownTimerUtils extends CountDownTimer {
- private View view;
- private long countDownInterval;
- private OnFinishListener listener;
- private OnTickListener tickListener;
- public interface OnFinishListener{
- void onFinishListener(View v);
- }
-
- public interface OnTickListener{
- void onTickListener(View v, long millisUntilFinished, long countDownInterval);
- }
- public CountDownTimerUtils(View view, long millisInFuture, long countDownInterval, OnTickListener tickListener, OnFinishListener listener){
- super(millisInFuture,countDownInterval);
- this.view=view;//倒计时相关组件 可以是TextView Button 等等
- this.countDownInterval=countDownInterval;//倒计时时长
- this.listener=listener;//倒计时结束监听
- this.tickListener=tickListener;//计时监听 相隔一秒调用
- }
-
- @Override
- public void onTick(long millisUntilFinished) {
- tickListener.onTickListener(view,millisUntilFinished,countDownInterval);
- }
-
- @Override
- public void onFinish() {
- listener.onFinishListener(view);
- }
- }
使用
- //对当前获取验证码控件进行倒计时相关设置
- CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(get_auth_code_tv, 60000, 1000, new CountDownTimerUtils.OnTickListener() {
- @Override
- public void onTickListener(View v, long millisUntilFinished, long countDownInterval) {
- TextView view = (TextView) v;
- view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.black));
- //设置不可用
- view.setEnabled(false);
- //设置倒计时时间
- view.setText("已发送(" + millisUntilFinished / countDownInterval + ")");
- }
- }, new CountDownTimerUtils.OnFinishListener() {
- @Override
- public void onFinishListener(View v) {
- TextView view = (TextView) v;
- view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.enabled_2_color));
- view.setText(R.string.get_auth_code);
- //重新获得点击
- view.setEnabled(true);
- }
- });
- countDownTimerUtils.start();//在需要的地方调用该方法启动倒计时