Android 如何在 countDownTimer 中使用 Interval

How to use Interval in countDownTimer in Android

在我的应用程序中我应该使用 CountDownTimer 为此我想使用这个库:CountdownView.
我想要持续 5 秒时显示 Toast.
例如:我想显示 17s countTimer,当这个计时器接收到 5s 时显示我 toast "just 5s".
我使用此代码,但显示 5s .

long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(5000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
    }
});

我只想持续 5 秒,而不是 5 秒。

我该怎么办?

我想你应该看看还剩多少秒。 我重写了你的代码:

long time1 = 17L * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        long remainTimeInSeconds = remainTime / 1000;
        if (remainTimeInSeconds  == 5) {
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});

通过修改您的代码:

boolean toastShown = false;
long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        if(remainTime < 5000 && !toastShown) {
            toastShown = true;
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});

您也可以试试这个代码:

CountDownTimer countDownTimer = new CountDownTimer(17000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        Toast.makeText(HomeActivity.this, "running" + millisUntilFinished, Toast.LENGTH_SHORT).show();
        if (millisUntilFinished < 5000) {
            Toast.makeText(HomeActivity.this, "5 sec left", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFinish() {
        Toast.makeText(HomeActivity.this, "Countdown Timer Finished", Toast.LENGTH_SHORT).show();
    }
};
countDownTimer.start();