如何为正在运行的倒数计时器增加时间?

时间:2014-02-14 12:23:36

标签: java android

在开始之前,我已经看过很多线程,包括:

How to add time to countdown timer? Android game countdown timer

但我不能让我的计时器以我需要的方式工作。我希望计时器从30开始倒计时,当按下图像时(在这种情况下命名为imageview1),计时器会给计时器增加3秒钟,以便给它更多时间。我知道你在运行时基本上不能添加时间,你需要取消然后启动一个新的计时器,我到目前为止的代码是:

public void onClick(View v) {
    // TODO Auto-generated method stub
    //GlobalClass global = new GlobalClass();
    Random rand = new Random();

    CountDownTimer thetimer = new myTimer(millisInFuture, 1000);

    switch(v.getId()) {

    case R.id.buttonstart:
        btnstart.setVisibility(View.INVISIBLE);     
        thetimer.start();   
        break;

    case R.id.imageView1:       
        if (thetimer != null){
            thetimer.cancel();
            thetimer = new myTimer(countdownPeriod + 3000, 1000).start();

        }

        break;

然后有很多其他案例参考:

public class myTimer extends CountDownTimer  {

         public myTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);          
        }

        @Override
        public void onTick(long millisUntilFinished) {          
                timedisplay.setText("Time Left: " + millisUntilFinished / 1000);
                countdownPeriod=millisUntilFinished;

        }

        @Override
        public void onFinish() {
            timedisplay.setText("Timer Finished");
            started = false;
            btnstart.setVisibility(View.VISIBLE);
        }
    }

我认为问题在于它没有取消原来的计时器,所以显示计时器的标签做了一些疯狂的事情,比如上下跳过不同的数字,因为会出现超过1类的定时器。即使我已经包含了行thetimer.cancel();如果我让它运行到0,计时器工作正常。

任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

您不应在onClick中将计时器创建为本地计时器。而是将其创建为全局并在其他位置启动它(也许在onCreate中)。

当前代码会发生的情况是,只要onClick被调用,就会创建一个新计时器,然后取消新计时器 - 这无效在任何先前创建的计时器上。

尝试这样的事情:

public class MyActivity extends Activity  {

   CountDownTimer thetimer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      thetimer = new myTimer(millisInFuture, 1000);
   }

   public void onClick(View v) {
      Random rand = new Random();
      switch(v.getId()) {
         case R.id.buttonstart:
            btnstart.setVisibility(View.INVISIBLE);     
            thetimer.start();   
            break;

         case R.id.imageView1:       
            if (thetimer != null) {
               thetimer.cancel();
               thetimer = new myTimer(countdownPeriod + 3000, 1000).start();
            }
            break;
      }   
   }    
}

你仍然需要跟踪某个地方的全球时间 - 即,当触摸图像时用于重新创建计时器实例的countDonwPeriod - 它应该在取消之前从计时器中提取出来。 / p>

相关问题