【问题标题】:Implementing counter in Android在 Android 中实现计数器
【发布时间】:2011-02-17 10:07:31
【问题描述】:

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

【问题讨论】:

标签: android


【解决方案1】:

我最好使用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();

【讨论】:

  • 有一个小类型this: CountDownTimer myCountDown = new CountdownTimer(3000, 1000) { 应该是这样的: CountDownTimer myCountDown = new CountDownTimer(3000, 1000) { 大写D在new CountDownTimer :)
  • 简单但确定!谢谢
【解决方案2】:

如下图使用CountDownTimer

第一步:创建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
        }
}

Step2:为该类创建一个对象

MyCount counter = new MyCount(2000, 1000); // set your seconds
counter.start();

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2012-05-26
    相关资源
    最近更新 更多