2017-12-06 9 views
0

私はこのボタンを持っており、クリックするとタイマーが作成されます。ボタンを押してカウントダウンタイマーを作成させ、それを再度クリックするとタイマーに時間を追加する方法

問題は、クリックごとにタイマーを作成することです。

ボタンを最初にクリックしてタイマーを作成してから、その後のすべてのクリックで、myTime変数にタイマーがなくなるまで5秒を追加します。

どうすればこの問題を解決できますか?

これは、ボタンがクリックされたときに実行されるコードです:

myTime = myTime + 5000 
    new CountDownTimer(myTime, 1000) { 

     public void onTick(long millisUntilFinished) { 
      myButton.setText("seconds remaining: " + millisUntilFinished/1000); 
     } 

     public void onFinish() { 
      myButton.setText("done!"); 
     } 
    }.start(); 
+0

あなたの友人を行く:ちょうどで[このスレッドをチェックアウト](https://stackoverflow.com/questions/17383584/how-to-add-time-to-countdown-timer) –

+0

削除混乱ライン/。 – MikeT

答えて

0

あなたはタイマーを削除して再起動する必要があります。最後のティックのミリ秒をキャプチャし、その5秒を追加します。あなたは多くの時間を失うことはありませんので、ダニを小さくしてください。ここで

CountDownTimer myTimer = null; 
long myTime = STARTING_TIME_IN_MILLIS; 
... 
// In the button click action performed event 

if (myTimer != null) { 
    myTimer.cancel(); // Cancel the existing timer 
    myTime = myTime + 5000; // Add five seconds to the remaining time. 
} 
// Start a new timer with the remaining time as the starting point. 
myTimer = new CountDownTimer(myTime, 100) { 
     public void onTick(long millisUntilFinished) { 
      myButton.setText("seconds remaining: " + millisUntilFinished/1000); 
      // Save the remaining time 
      myTime = millisUntilFinished; 
     } 

     public void onFinish() { 
      myButton.setText("done!"); 
     } 
}.start(); 
+0

申し訳ありませんが、どこに "CountDownTimer myTimer = null;"を入れていますか?私はあまりよく分からない。それはcreate関数かクラスの中にあるべきですか? – Berkly

+0

https://pastebin.com/Tt26Ni7s – Berkly

+0

@Berkly。それはよさそうだ。それはあなたのために働くのですか? –

関連する問題