显示处理程序的剩余时间

时间:2019-02-27 15:56:38

标签: android handler countdown countdowntimer

我想知道如何显示处理程序中的剩余时间。 当我单击按钮时,我的处理程序运行了x秒钟,我想在处理程序结束之前在屏幕上显示倒计时。

3 个答案:

答案 0 :(得分:0)

尝试一下:

    int time = 60;  // seconds
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            time--;
            mTextView.setText(time + " seconds");
        }
    };
    handler.postDelayed(runnable, 1000);

答案 1 :(得分:0)

official documentation

  

在文本字段中显示30秒倒计时的示例:

[error]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(3049,5): 
Error MSB3552: Resource file "Properties\Resources.resx" cannot be found.

答案 2 :(得分:0)

  

效果很好,谢谢,最后一个细节,如果我放5秒,它显示:5、4、3、2、1和0。最后是6秒。

马克西姆,正如我在您对托马斯·玛丽的回答的评论中所读到的那样,您希望避免额外调用onTick()。

您之所以会看到这种情况,是因为CountDownTimer的original implementation在计时器启动时(没有延迟)第一次调用onTick()。

  

如何删除结尾的0?

为此,您可以使用经过修改的CountDownTimer:

public abstract class CountDownTimer {

private final long mMillisInFuture;
private final long mCountdownInterval;
private long mStopTimeInFuture;

private boolean mCancelled = false;

public CountDownTimer(long millisInFuture, long countDownInterval) {
    mMillisInFuture = millisInFuture;
    mCountdownInterval = countDownInterval;
}

public synchronized final void cancel() {
    mCancelled = true;
    mHandler.removeMessages(MSG);
}

public synchronized final CountDownTimer start() {
    mCancelled = false;
    if (mMillisInFuture <= 0) {
        onFinish();
        return this;
    }
    mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
    onTick(mMillisInFuture);
    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG), mCountdownInterval);
    return this;
}

public abstract void onTick(long millisUntilFinished);

public abstract void onFinish();

private static final int MSG = 1;

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        synchronized (CountDownTimer.this) {
            if (mCancelled)
                return;
            final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
            if (millisLeft <= 0) {
                onFinish();
            } else {
                onTick(millisLeft);
                sendMessageDelayed(obtainMessage(MSG), mCountdownInterval);
            }
        }
    }
};
}

请注意,您可能需要相应地在onTick()方法中调整实现。