How to delay a loop in android without using thread.sleep?
You can use a Handler
instead of for loop. You should not call Thread.sleep()
on the UI thread.
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// do something
handler.postDelayed(this, 1000L); // 1 second delay
}
};
handler.post(runnable);
The following code doing the task in every second:
final Handler handler = new Handler();
Runnable task = new Runnable() {
@Override
public void run() {
Log.d(TAG, "Doing task");
handler.postDelayed(this, 1000);
}
};
handler.post(task);
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.
Edited for syntax