我有一个应用程序,我需要从3到1显示计数器然后快速切换到另一个活动。 TimerTask会不适合这样做?有人能告诉我一个如何做到这一点的例子吗?
CountDownTimer工作。显示计时器3秒的代码是。
new CountDownTimer(4000, 1000) {
public void onTick(long millisUntilFinished) {
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(countdown.this, R.anim.fadeout);
counter.startAnimation(myFadeOutAnimation);
counter.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() {
counter.setText("done!");
}
}.start();
答案 0 :(得分:14)
我最好使用CountDownTimer。
如果您想要计数器计数3秒:
//new Counter that counts 3000 ms with a tick each 1000 ms
CountDownTimer myCountDown = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
//update the UI with the new count
}
public void onFinish() {
//start the activity
}
};
//start the countDown
myCountDown.start();
答案 1 :(得分:2)
使用CountDownTimer
,如下所示。
第1步:创建CountDownTimer
类
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
dialog.dismiss();
// Use Intent to Navigate from this activity to another
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}
第二步:为该类创建一个对象
MyCount counter = new MyCount(2000, 1000); // set your seconds
counter.start();