之前写的倒计时,用的TimerTask与Handler
今天发现Google已经给写了一个类CountDownTimer,专门做倒计时功能的,分享一下。
private CountDownTimer timer = new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
btSendVerificationCode.setText(String.format("稍等%s秒", millisUntilFinished / 1000));
}
@Override
public void onFinish() {
tvChangePhone.setEnabled(true);
tvChangePhone.setTextColor(getResources().getColor(R.color.blue_low));
tvChangePhone.setEnabled(true);
tvChangePhone.setTextColor(getResources().getColor(R.color.blue_low));
btSendVerificationCode.setEnabled(true);
btSendVerificationCode.setText("发送验证码");
btSendVerificationCode.setBackgroundResource(R.drawable.bg_corners_blue);
if (!isInputPhone) {
tvHint.setText("短信验证码将发送至");
}
}
};
调用的时候很简单:timer.start();
取消:timer.cancel();
最后说明一下:CountDownTimer timer = new CountDownTimer(60000, 1000)中,第一个参数表示总时间,第二个参数表示间隔时间。意思就是每隔一秒会回调一次方法onTick,然后60秒之后会回调onFinish方法。