4

我有一个带有倒数计时器的 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();

}
4

2 回答 2

17

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

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();
}
于 2012-06-05T21:15:06.993 回答
3

调用cancel()CountDownTimer 上的方法

于 2012-06-05T21:16:51.377 回答