简体   繁体   English

如何访问CountDownTimer以在Java中取消它?

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

Making a small game in Android Studio. 在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. 我的CountDownTimer对象与按钮单击处理程序位于不同的函数内。 How can I cancel the countDownTimer using cancel() from the button click handler. 如何从按钮单击处理程序中使用cancel()取消countDownTimer。

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();
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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