在Android中实现计数器

Aya*_*avi 2 android

我有一个应用程序,我需要显示从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();
Run Code Online (Sandbox Code Playgroud)

mai*_*450 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();
Run Code Online (Sandbox Code Playgroud)