如何在不使用thread.sleep的情况下延迟android中的循环? [英] How to delay a loop in android without using thread.sleep?
问题描述
我想在不使用 Thread.sleep
的情况下延迟for循环,因为该方法会使我的整个应用程序挂起。我试图使用处理程序
但它似乎不能在循环内工作。有人可以指出我的代码中的错误。
I wanted to delay a for loop without using Thread.sleep
because that method make my whole application hang. I tried to use handler
but it doesn't seems to work inside a loop. Can someone please point out the mistake in my code.
public void onClick(View v) {
if (v == start)
{
for (int a = 0; a<4 ;a++) {
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
ImageButton[] all= {btn1, btn2, btn3, btn4};
btn5 = all[random.nextInt(all.length)];
btn5.setBackgroundColor(Color.RED);
@Override
public void run() {
}
}, 1000);
}
}
}
基本上我想做什么是我有4 ImageButton
,我按顺序使用循环将每个背景更改为红色。这就是为什么我需要在我的循环中延迟,如果不是所有 ImageButton
将直接变为红色而不显示哪个 ImageButton
先转。
Basically what I wanted to do is that I got 4 ImageButton
and I change each of their background to red by using a loop in order. Thats why I need a delay inside my loop, if not all the ImageButton
will just directly turn red without showing which ImageButton
turn first.
推荐答案
你的for循环应该是:
Your for loop should be:
final ImageButton[] all= {btn1, btn2, btn3, btn4};
Handler handler1 = new Handler();
for (int a = 1; a<=all.length ;a++) {
handler1.postDelayed(new Runnable() {
@Override
public void run() {
ImageButton btn5 = all[random.nextInt(all.length)];
btn5.setBackgroundColor(Color.RED);
}
}, 1000 * a);
}
}
这样可以达到你想要的颜色交错的行为更改。
This way it achieves your desired behavior of staggering the color change.
编辑语法
这篇关于如何在不使用thread.sleep的情况下延迟android中的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!