2014-05-12 82 views
0

我想創建一個活動時啓動一個計時器,並能夠從零重置計時器,如果按下相同的按鈕,但每次按下啓動設置時間間隔的按鈕時,它似乎都會創建一個新的時間間隔而不是重置已經創建的那個。有人可以幫忙嗎?這裏是我的代碼如何在計時器完成時重置計時器值?

timer = (TextView) findViewById(R.id.timer_value); 

Count = new CountDownTimer(time, 1000) { 

     public void onTick(long millisUntilFinished) { 

      timer.setText("Time Left: " + millisUntilFinished/1000); 
     } 

     public void onFinish() { 
      timer.setText("OUT OF TIME!"); 
      if (time < 10000) { 
       time = 10000; 
      } 
      AlertDialog.Builder builder = new AlertDialog.Builder(
        TicTacToe.this); 
      builder.setMessage("You are Out of Time").setPositiveButton(
        "Replay", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // reset the game environment. 

          Count.onFinish(); 
          // Count.cancel(); 
          Count.start(); 
          new_game(player_name_1); 
         } 
        }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 

     } 
    }.start(); 

回答

0

您可以使用定時器

//in global 
Timer myTimer 


/** 
* its kills runnable 
*/ 
public void stopTimer(){ 
//handler.removeCallbacks(null); //it resets all timer which handler holds 
myTimer.cancel(); 
} 

public void setTimer(int time){//give it 5 for 5 secs 
final Runnable Update = new Runnable() { 

     public void run() { 
      //do sth 
     } 
    }; 

    myTimer = new Timer(); 
    myTimerTimer.schedule(new TimerTask() { 

     @Override 
     public void run() { 
      handler.post(Update); 
     } 
    }, 1000, time*1000); 
} 
+0

但我有一個指定的時間爲countDownTimer我怎麼能實現這一點,並作爲我的問題如何停止和重置計時器完成之間的計時器值和重置計時器的值。你現在可以幫我@alp –

0

如果要重新啓動定時器,刪除Count.onFinish();

更新:
我取代AlertDialog一個新的線程,這裏是我的模擬器上的代碼

public class MainActivity extends Activity 
{ 
    int time = 10000; 
    CountDownTimer Count; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final TextView timer = (TextView) findViewById(R.id.timer); 

     Count = new CountDownTimer(time, 1000) { 

      public void onTick(long millisUntilFinished) { 

       timer.setText("Time Left: " + millisUntilFinished/1000); 
      } 

      public void onFinish() { 
       timer.setText("OUT OF TIME!"); 
       if (time < 10000) { 
        time = 100000; 
       } 
      } 
     }.start(); 
    } 
    public void buttonClicked(View view) 
    { 
     Log.i("Timer", "Resetting timer"); 
     Count.cancel(); 
     Count.start(); 
    } 

} 
+0

但它不工作它生成一個新的計時器與不同的價值,我已經刪除,但它不工作 –

+0

讓我檢查我會讓你知道 –

+0

但@helleye,因爲我問過的問題是,我要使用按鈕單擊完成定時器之前,要從零開始重新啓動它。請考慮一下,感謝您的幫助,但不是我的問題「您提供給我的解決方案」 –