gpt4 book ai didi

java - 如何在两个for循环中分别使用postDelayed或sleep两次

转载 作者:行者123 更新时间:2023-11-29 23:17:52 24 4
gpt4 key购买 nike

我想数 5 秒并启动一个函数。该函数还需要每 3 秒调用一次。

Toast.makeText(this, "Countdown 5", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();

for (int i = 5; i >= 0; --i) {
final int idx = i;
handler.postDelayed(() -> {
Toast.makeText(MyActivity.this, "Countdown " + (idx - 1), Toast.LENGTH_SHORT).show();
if (idx == 0) {
int messageSize = messageItems.size();
for (int j = 0; j < messageSize; j++) {
final int jdx = j;
Handler handler1 = new Handler();
handler1.postDelayed(() -> {
Toast.makeText(MyActivity.this, messageItems.get(jdx), Toast.LENGTH_SHORT).show();
}, 3000 * jdx);
}
}
}, 1000 * (5-idx));
}

内循环部分在没有外循环的情况下工作良好。

        int messageSize = messageItems.size();
for (int j = 0; j < messageSize; j++) {
final int jdx = j;
Handler handler1 = new Handler();
handler1.postDelayed(() -> {
Toast.makeText(MyActivity.this, messageItems.get(jdx), Toast.LENGTH_SHORT).show();
}, 3000 * jdx);
}

我想添加一个功能,例如 5 秒倒计时。然后启动 Toast Message。而Toast消息也需要每3秒吐一次。

最佳答案

试试这段代码。这给出了相当准确的结果。有时会有一些滞后,但不会引人注意。 Tweek 这个来展示你的 toast 。

    int counter = 5;
Handler handler = new Handler();

ArrayList<String> messageItems = new ArrayList<>();
messageItems.add("Message 1");
messageItems.add("Message 2");
messageItems.add("Message 3");

Runnable runnable = new Runnable() {
@Override
public void run() {
counter--;
if (counter > 0) {
Log.d("HOME", "onCreate: countdown " + counter + " " + System.currentTimeMillis());
handler.postDelayed(this, 1000);
}
if (counter == 1) {
for (int j = 0; j < messageItems.size(); j++) {
final int jdx = j;
Handler handler1 = new Handler();
handler1.postDelayed(() -> {
Log.d("HOME", "onCreate: countdown " + messageItems.get(jdx) + " " + System.currentTimeMillis());
}, 3000 * jdx);
}
}
}
};

Log.d("HOME", "onCreate: countdown 5 " + System.currentTimeMillis());
handler.postDelayed(runnable, 1000);

以下是计时的输出 -

Countdown 5 1551720212370
+1004
Countdown 4 1551720213374
+1019
Countdown 3 1551720214393
+1013
Countdown 2 1551720215406
+1568
Countdown 1 1551720216974
+413
Message 1 1551720217387
+2589
Message 2 1551720219976
+2999
Message 3 1551720222975

关于java - 如何在两个for循环中分别使用postDelayed或sleep两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com