倒计时工具


//在这个构造方法里需要传入三个参数,一个是Activity,一个是总的时间millisInFuture,
// 一个是每次减少的时间,最后一个是显倒计时的按钮
用法:
TimeLastUtil  timeLastUtil = new TimeLastUtil(this, 60000, 1000, btn);

timeLastUtil.start();

实体类

public class TimeLastUtil extends CountDownTimer {

   private Activity mActivity;
   private TextView btn;// 按钮

   //在这个构造方法里需要传入三个参数,一个是Activity,一个是总的时间millisInFuture,
   // 一个是countDownInterval,然后就是你在哪个按钮上做这个是,就把这个按钮传过来就可以了
   public TimeLastUtil(Activity mActivity, long millisInFuture,
                  long countDownInterval, TextView btn) {
      super(millisInFuture, countDownInterval);
      this.mActivity = mActivity;
      this.btn = btn;
   }

   

   @SuppressLint("NewApi")
   @Override
   public void onFinish() {
      btn.setText(R.string.register_regetchecknum);
      btn.setClickable(true);// // 重新获得点击
      btn.setBackgroundColor(Color.parseColor("#00CCCC"));// 还原背景色
   }

   @Override
   public void onTick(long millisUntilFinished) {
      btn.setClickable(false);// 设置不能点击
      btn.setText(millisUntilFinished / 1000 + "s后可重新发送");// 设置倒计时时间

      // 设置按钮为灰色,这时是不能点击的
      btn.setBackgroundColor(Color.GRAY);
      Spannable span = new SpannableString(btn.getText().toString());// 获取按钮的文字
      span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE);// 讲倒计时时间显示为红色
      btn.setText(span);

   }

}

 
 
原文地址:https://www.cnblogs.com/zhou2016/p/5306079.html