前言
60秒倒计时的功能,我们经常见到,看到过一些例子,通过自定义实现,比较复杂,今天我们就利用系统提供的CountDownTimer实现倒计时功能。
CountDownTimer源码
public abstract class CountDownTimer {
/**
* millisInFuture 倒计时的总毫秒数
* countDownInterval 时间间隔,也是毫秒单位
*/
public CountDownTimer(long millisInFuture, long countDownInterval) {
throw new RuntimeException("Stub!");
}
public final synchronized void cancel() {
throw new RuntimeException("Stub!");
}
public final synchronized CountDownTimer start() {
throw new RuntimeException("Stub!");
}
/**
* 倒计时的方法
*/
public abstract void onTick(long var1);
public abstract void onFinish();
}
10秒倒计时Demo
public class MainActivity extends AppCompatActivity {
Button buton;
MyCountTimer timer;
boolean isTick = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button)findViewById(R.id.tv_text);
timer = new MyCountTimer(10200,1000);
buton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isTick){
timer.start();
isTick = !isTick;
}
}
});
}
public class MyCountTimer extends CountDownTimer{
public MyCountTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long l) {
buton.setText(l/1000+"秒");
}
@Override
public void onFinish() {
buton.setText("获取验证码");
isTick = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
isTick = false;
}
}
细心的朋友可能发现了,Demo明明是10s倒计时,但是代码中的总秒数是10200,为什么要这样写呢?我们先看下如果写10000,所打出的log:
Paste_Image.png
这样展示的结果就是:5,3,2,1
原因是CountDownTimer是有几秒的误差,所以我们需要自己多加一些,比如60s倒计时你就写60200或者60100都行,就会解决上面的问题。