【问题标题】:How Do I Let A Button Create A Countdown Timer, And Then Whenever It Is Clicked Again Add Time To The Timer?我如何让一个按钮创建一个倒数计时器,然后每当再次单击它时将时间添加到计时器?
【发布时间】:2017-12-06 21:39:34
【问题描述】:

我有这个按钮,当它被点击时,它会创建一个计时器。

问题是,它每次点击都会创建一个计时器。

我希望这个按钮做的是在第一次点击时创建一个计时器,然后在所有后续点击中为 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();

【问题讨论】:

标签: java timer countdowntimer


【解决方案1】:

您需要删除计时器并重新启动它。捕获最后一个滴答声的毫秒数,然后加上你的 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();

【讨论】:

  • 对不起,我把“CountDownTimer myTimer = null;”放在哪里了?我不太确定。它应该在创建函数中还是仅仅在类中?
猜你喜欢
  • 1970-01-01
  • 2020-07-29
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多