0

好的,所以我有一个倒数计时器,我的应用程序要求用户多次点击一个按钮,但是计时器在该按钮点击时开始。我的问题是:

我有一个 10 秒的倒计时计时器,它在按下按钮时开始,但不是仅仅持续到 0,而是在每次用户点击按钮时从 10 重新开始。我如何做到这一点,当用户第一次点击它时,它会一直倒计时?

我的代码:

private Button tapBtn;
TextView cm;

tapBtn = (Button) findViewById(R.id.Tap);
cm = (TextView) findViewById(R.id.Timer);

final CountDownTimer aCounter = new CountDownTimer(10000, 1000) {

         public void onTick(long millisUntilFinished) {
            cm.setText("Time Left: " + millisUntilFinished / 1000);
         }

         public void onFinish() {
             cm.setText("Time's Up!");
         }
      };
      aCounter.cancel();

tapBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            scr = scr - 1;
            TextView Score = (TextView) findViewById(R.id.Score);
            Score.setText(String.valueOf(scr));
            aCounter.start();
        }
    });
}
4

2 回答 2

1

Are you trying to make it so that if the user has already started the timer, subsequent button presses don't restart it from the first tap? If so, all you should have to do is put an if statement in your onclick that checks to see if the timer is still counting down, i.e. check and see if the current time is greater than 0 on the counter.

Edit: here's code

final CountDownTimer aCounter = new CountDownTimer(10000, 1000) {

         private long timeLeft;

         public long getTimeLeft() {
            return timeLeft;
         }

         public void onTick(long millisUntilFinished) {
            timeLeft = millisUntilFinished / 1000;

            cm.setText("Time Left: " + timeLeft);

         }

         public void onFinish() {
             cm.setText("Time's Up!");
         }
      };
      aCounter.cancel();

tapBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (aCounter.getTimeLeft() == 0) {
               scr = scr - 1;
               TextView Score = (TextView) findViewById(R.id.Score);
               Score.setText(String.valueOf(scr));
               aCounter.start();
            }
        }
    });
}
于 2012-08-17T20:04:19.530 回答
0

one way to do it is to create a flag that gets set on the first tap and have the onclick event flip the flag on the first click, and put the timer start inside of an if statement that only occurs if the flag hasn't been set.

于 2012-08-17T20:05:24.980 回答