简体   繁体   中英

How do I access my CountDownTimer to cancel it in Java?

Making a small game in Android Studio. Basically, the user will have a set amount of time to trigger a button press or the game will end. My CountDownTimer object is inside of a different function than my button click handler. How can I cancel the countDownTimer using cancel() from the button click handler.

Here is my code:

public countDownTimer timeLimit;

public void generate() {
    final ProgressBar timer = (ProgressBar)findViewById(R.id.timer);`
        int timeoutSeconds = 5000;
        timer.setMax(timeoutSeconds);
        timeLimit = new CountDownTimer(timeoutSeconds, 100) {

            public void onTick(long millisUntilFinished) {
                int timeUntilFinished = (int) millisUntilFinished;
                timer.setProgress(timeUntilFinished);
            }

            public void onFinish() {
                gameOver();
            }
        };
        timeLimit.start();
}

public void buttonClicked(View v) {
    timeLimit.cancel();
}

I'd be happy to hear any alternative ways to do this as well.

The code below works perfectly for me.  

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private ProgressBar progressBar;
private CountDownTimer countDownTimer;
private Button stopTimerButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressBar = (ProgressBar)findViewById(R.id.progressBar);
    stopTimerButton = (Button)findViewById(R.id.button);
    stopTimerButton.setOnClickListener(this);
    int timeoutSeconds = 5000;
    progressBar.setMax(timeoutSeconds);
    countDownTimer = new CountDownTimer(timeoutSeconds,100) {
        @Override
        public void onTick(long millisUntilFinished) {
            int timeUntilFinished = (int) millisUntilFinished;
            progressBar.setProgress(timeUntilFinished);
        }

        @Override
        public void onFinish() {

        }
    };
    countDownTimer.start();

}

@Override
public void onClick(View view) {
    if(view == stopTimerButton){
        countDownTimer.cancel();
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM