创建 CountDownTimer 对象的方法

Method creating CountDownTimer objects

我有点受困于以下代码。我的目标是创建多个 CountDownTimer 对象并依次启动它们。该方法如下所示:

    private CountDownTimer setUpCountdown(int duration, int tick) {
    // when tick is not set, set it to default 1 second
    tick = (tick == 0 ? 1 : tick);

    // convert seconds to milliseconds and set up the timer
    CountDownTimer timer = new CountDownTimer(duration*1000, tick*1000) {

        public void onTick(long millisUntilFinished) {
            if (countdown != null) {
                int timeRemaining = (int) (millisUntilFinished / 1000);
                countdown.setText(String.valueOf(timeRemaining));
            }
        }

        public void onFinish() {
            // hide the countdown button and remove it from baseLayout. set the background of baseLayout back to black
            countdown.setVisibility(View.INVISIBLE);
            baseLayout.removeView(countdown);
            baseLayout.setBackgroundColor(Color.BLACK);
        }
    };

    return timer;
}

然后我创建两个计时器:

CountDownTimer timer1 = setUpCountdown(8,1);
timer1.start();
CountDownTimer timer2 = setUpCountdown(5,1);
timer2.start();

当 运行 代码时,这些值的输出是:4..3..2..1..3 而它应该是 7..6...1 4...1当我使用 10 秒和 5 秒作为持续时间时,我在 android 设备上得到一个从 10 到 5 的倒计时。看起来我正在创建的对象并不是真正独立于彼此或(种类of) 使用相同的变量。你看到我做错了什么了吗?

您同时启动两个计时器并在单个 textView 中显示它们的值,因此您只能看到第二个计时器的值 4..1,然后计时器的剩余值 8秒将显示为3..1

timer 7 6 5 4  3 2 1
// timer 2 will reset the values in text view, then after 1, you will see 3 2 1
timer 4 3 2 1 

您可以使用 Toast 来验证行为,或者您必须使用不同的 TextViews 来获得所需的结果或实现所需的行为,您可以从 [= 创建并启动第二个计时器17=]