利用Android中自带的CountDownTimer实现手机验证码倒计时
public class TimeCountUtil extends CountDownTimer {
private static final int TIME_TASCK = 1000;
private Button button;
public TimeCountUtil(long millisInFuture, Button view) {
//millisInFuture倒计时总时间
super(millisInFuture, TIME_TASCK);
button = view;
}
@Override
public void onFinish() {// 计时完毕
button.setText("发送验证码");
button.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished) {// 计时过程
button.setClickable(false);//防止重复点击
button.setText("("+(millisUntilFinished / TIME_TASCK)+")后重新发送");
}
}
使用
//每次调用的时候只需要调用start()方法即可
mTimeCount.start();
另外,为了节省资源,在Activity销毁时应该停止倒计时:
@Override
protected void onDestroy() {
super.onDestroy();
mTimeCount.cancel();
}