Search code examples
javaandroidbuttoncountdown

Cancel Button During Countdown


Quick question here, I have the following code working for the most part, but I would like for the button to go back to it's original state if it is clicked during the countdown. Any suggestions?

            button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                new CountDownTimer(4000, 1000) {

                    @Override
                    public void onFinish() {
                        button.setText("SENT");                 

                    }

                    @Override
                    public void onTick(long sec) {
                        button.setText("CANCEL (" + sec / 1000 + ")");
                        button.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                cancel();

                            }

                        });

                    }
                }.start();
            }
        });

Before the button is ever pressed, it will say "Push Me." Once pressed, the countdown will begin and the button's text will change each second (CANCEL (3), CANCEL (2), CANCEL (1)) and after the countdown the button will update its text to "SENT." If the button is pressed during the countdown (onTick), it will cancel the countdown. I would like to know how to make it revert to the "Push Me" state, and basically allow it to be pressed again and begin a new countdown. Any help would be appreciated!


Solution

  • So you should not have a new onClickListener inside of the timer because that uses a lot more memory then is needed, and may cause unexpected results. Instead I would suggest using a boolean value for if the timer is on, and use your existing button's onClickListener. Make sure that your timer is declared globally if you are using this. Here is an example of how that might work:

        button.setOnClickListener(new OnClickListener {
            if(timerIsOn){
              if(timer != null){
                timer.cancel();
                timerIsOn = false;
              }
            }
            else{
            timerIsOn = true;
            //start the timer and do whatever else
            }
        }