gpt4 book ai didi

java - 你如何取消 CountDownTimer?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:22 26 4
gpt4 key购买 nike

我有一个带有倒数计时器的 AlertDialog,我有一个取消按钮设置,它取消了对话框,但计时器继续运行!有谁知道如何取消倒数计时器的倒计时?任何帮助将不胜感激!

   private void timerDialog() {
timerDialog = new AlertDialog.Builder(this).create();
timerDialog.setTitle("Timer");
timerDialog.setMessage("Seconds Remaining: "+timerNum*1000);
timerDialog.setCancelable(false);
timerDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface aboutDialog, int id) {
timerDialog.cancel();
}
});
timerDialog.show();
new CountDownTimer(timerNum*1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timerDialog.setMessage("Seconds Remaining: "+ (millisUntilFinished/1000));
}

@Override
public void onFinish() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
timerDialog.cancel();
}
}.start();

}

最佳答案

您似乎在对话框上调用取消,但从未在计时器上调用。您需要维护对 CountDownTimer 的引用,并在您的 onClick 方法中调用它的 cancel 方法。

private void timerDialog() {
final CountDownTimer timer = new CountDownTimer(timerNum*1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timerDialog.setMessage("Seconds Remaining: "+ (millisUntilFinished/1000));
}

@Override
public void onFinish() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
timerDialog.cancel();
}
};
timerDialog = new AlertDialog.Builder(this).create();
timerDialog.setTitle("Timer");
timerDialog.setMessage("Seconds Remaining: "+timerNum*1000);
timerDialog.setCancelable(false);
timerDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface aboutDialog, int id) {
timer.cancel();
}
});
timerDialog.show();
timer.start();
}

关于java - 你如何取消 CountDownTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10904933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com