my timer in eclipse did not work properly

2019-03-05 04:09发布

I am new to eclipse and my timer in eclipse did not work properly, this is my java. code in the timer:

Button countDownButton2 = (Button) findViewById(R.id.countDown1);      
    countDownButton2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view){

              CountDownTimer timer2 = new CountDownTimer(3000,1000){

                    @Override
                    public void onFinish() {

                        mTimeLabel1.setText("Times Up baby!");
                    }

                    @Override
                    public void onTick(long millisUntilFinished) {                               

                          int seconds = (int) (millisUntilFinished / 1000);
                          int minutes = seconds / 60;
                          seconds = seconds % 60;

                          mTimeLabel1.setText("" + minutes + ":"
                                                          + String.format("%02d", seconds));

                    }          
              }.start();

        }
    });

Basically everything is running as I wish, however, I found that if I clicked the trigger button while it is counting, it will trigger another counting without stop the previous counting. This is very embarrassing, my friend suggest me to do "switch" if the button trigger again, and I am considering to add another actions to the same button which is stop the restart counting. Which one is more preferable?

1条回答
地球回转人心会变
2楼-- · 2019-03-05 05:07

Disable the trigger button while the timer is running.

That way you will save the pain to fiqure out how to do a switch or adding other actions to the button after the first click.

You could try the yourbutton.setEnabled(false); to make it disabled.

if i have understood the code right, it should be

countDownButton2.setEnabled(false);

To enable the button again, use

countDownButton2.setEnabled(true);

查看更多
登录 后发表回答