"定时器吐司"显示滞后然后实际"倒数计时器"

时间:2015-02-05 06:43:23

标签: android countdowntimer android-toast

我在Toast内使用Countdown Timer显示时间秒,但我觉得Toast的显示实际上落后于实时秒,是否有更好的方式来显示消息好吗?

CountDownTimer timer = new CountDownTimer(20000, 1000) {

    @Override
    public void onTick(long millisUntilFinished) {

        Toast.makeText(getApplicationContext(), "Disabling Task, Please wait : " + millisUntilFinished/1000, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFinish() {
        Toast.makeText(getApplicationContext(), "Congratulations!! Time out", Toast.LENGTH_SHORT).show();
    }
}.start();  

1 个答案:

答案 0 :(得分:1)

问题是toast被添加到队列中并一个接一个地执行。您的刻度线比导致延迟的Toast.LENGTH_SHORT更快。你想要保留对前一个吐司的引用,并在显示一个新的之前取消它。

Toast mToast = null;

CountDownTimer timer = new CountDownTimer(20000, 1000) {

    @Override
    public void onTick(long millisUntilFinished) {
        if (mToast != null) mToast.cancel();
        mToast = Toast.makeText(getApplicationContext(), "Disabling Task, Please wait : " + millisUntilFinished/1000, Toast.LENGTH_SHORT);
        mToast.show();
    }

    @Override
    public void onFinish() {
        if (mToast != null) mToast.cancel();
        mToast = Toast.makeText(getApplicationContext(), "Congratulations!! Time out", Toast.LENGTH_SHORT);
        mToast.show();
    }
}.start();

警告!这不适用于Android 2.3。