Android 简单实现倒计时功能简单实现倒计时功能
在 Android 中倒计时功能是比较常用的一个功能,比如短信验证码,付款倒计时等。实现方式有Handler、Thread 等,但是实
现起来都有点麻烦,其实Android已经为我们封装好了一个抽象类 CountDownTimer,可以简单的实现倒计时功能,如下图所
示。
CountDownTimer 实现倒计时功能的机制也是用Handler 消息控制,只是它帮我们已经封装好了,先看一下它的介绍。
Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a
text field:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText(“done!”);
}
}.start();
大致意思是,设置一个倒计时,直到完成这个时间段的计时,并会实时更新时间的变化,最后举了一个30秒倒计时的例子,
如下:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
详解
可以看到,上面示例中构造方法需要传入两个参数,如下:
/**
* @param millisInFuture The number of millis in the future from the call to start()
* until the countdown is done and onFinish() is called.
* @param countDownInterval The interval along the way to receive onTick(long) callbacks.
*/
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
评论0