使用背景:
一个比较常见到的功能:app在注册或者是找回密码等操作时,需要获取短信验证码,在点击了获取短信验证码的按钮后,就会出现倒计时,按钮变成不可点击状态,当倒计时结束后,如果你没有获取到验证码,可以再次点击。这个功能可以通过官方提供的CountDownTimer来简单实现!
官方文档:
比较简单,直接给出了一个例子,就是实现了一个时间间隔为1秒,总时长3秒的倒计时任务:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
实际使用:
new CountDownTimer(60100,1000) {
public void onTick(long millisUntilFinished) {
sendPasswordButton.setText(millisUntilFinished / 1000 + "秒后重发");
sendPasswordButton.setEnabled(false);
sendPasswordButton.setBackground(mContext.getResources().getDrawable(R.drawable.round_button_login_sendtimer)); }
@Override
public void onFinish() {
sendPasswordButton.setText("发送动态密码");
sendPasswordButton.setEnabled(true);
sendPasswordButton.setBackground(mContext.getResources().getDrawable(R.drawable.round_button_login_sendnormal));}
}.start();
注意细节:
在设置总时长的时候最好在整秒数的基础上加一点,不然有可能会出现设置了8秒,但是直接从8秒到6、5、4...的现象,谨记!