-3

我想延迟几秒钟并显示 Toast,我尝试SystemClock.sleep

但它只显示最后一条消息(“10s”)......

Toast.makeText(MainActivity.this,"1s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"5s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"10s", Toast.LENGTH_SHORT).show();

那应该是按1s、5s、10s的顺序显示不是吗?

我也参考了这个做法,但是无法实现…… 如何在android中设置延迟?

那么问题出在哪里?

4

1 回答 1

5

尝试处理程序

public void showToast(final String message, int timeInMilliSeconds, final Context context) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }
    };
    Handler handler = new Handler();
    handler.postDelayed(runnable, timeInMilliSeconds);
}

用法:

showToast("1s, 1000, this);
showToast("5s, 5000, this);
showToast("10s, 10000, this);
于 2015-12-09T03:31:15.370 回答