2011-03-28 122 views
2

你好我有CountDownTimer功能的問題取消並重新啓動CountDownTimer問題

第一,我可以得到它停止與counter.cancel倒計時(); 然後我在countercur中存儲milliUntilFinished值。

然後我使用存儲的countercur值重新啓動計時器。 這一切工作正常。但是當我第二次嘗試取消時,它再也不會停止計時器。 只是一次,我錯過了什麼?這裏是我的代碼感謝:

// Main code : 
MyCount counter = new MyCount(59000, 1000); 
      counter.start(); // start timer at 59 seconds 

/// 

button1.setOnClickListener(new View.OnClickListener() { 


    public void onClick(View v) { 
counter.cancel(); // -- > cancelling the timer works here, the clock stops ok 
// 
// rest of code snipped 

button2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
     MyCount counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled 

      counter.start(); // This restarts timer ok. when when retrying button 1 to cancel again, it never cancels. 

// rest of code snipped 

// Timer Setup 
    public class MyCount extends CountDownTimer { 

     public MyCount(long millisInFuture, long countDownInterval) { 

     super(millisInFuture, countDownInterval); 
     }  
     public void onFinish() { 
Intent intent = new Intent(); 
      intent.setClass(Main.this, Final.class); 
      startActivity(intent); 
      } 
      else { 
      MyCount counter = new MyCount(59000, 1000); 
      counter.start(); 
      clock = counter.toString(); 
      } 

     }  
     public void onTick(long millisUntilFinished) { 
      //int min = 5; 
      /*if (+millisUntilFinished/1000 <= 240) { 
       min = 4; 
       mintosec = "240"; 

       //millisUntilFinished = 59000; 
      } 
      else if (+millisUntilFinished/1000 <= 180) { 
       min = 3; 
       mintosec = "180"; } 
      else if (+millisUntilFinished/1000 <= 120) { 
       min = 2; 
       mintosec = "120"; } 
      else if (+millisUntilFinished/1000 <= 60) 
       min =1; 
       mintosec = "60"; */ 

      //TextView totmin = (TextView) findViewById(R.id.clockmin); 
      //totmin.setText(""); 
      TextView totsec = (TextView) findViewById(R.id.clocksec); 
      totsec.setText(+duration +" : "+ millisUntilFinished/1000); 
      countcur = millisUntilFinished; // store current count value for pausing and restarting 
     } 
    } // End Timer 

回答

3

在下面,要設置一個局部變量,而不是類變量:

button2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
     MyCount counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled 

將其更改爲引用現有的類變量,而不是:

button2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
    counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled 
+0

這個伎倆!非常感謝你。 – huskyd97 2011-03-28 04:46:35

+0

沒問題。不要忘了標記接受的答案,如果它解決了你的問題! – squawknull 2011-03-28 04:52:33