Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay a loop in android without using thread.sleep?

Tags:

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);         }          }      } 

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.

like image 923
user3153613 Avatar asked Jan 03 '14 03:01

user3153613


People also ask

How do you add a delay between lines in Java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.

What is time delay loop in Java?

These are loops that have no other function than to kill time. Delay loops can be created by specifying an empty target statement. For example: for(x=0;x<1000;x++); This loop increments x one thousand times but does nothing else.

What is thread sleep in Android?

A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to use thread. sleep() in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.


2 Answers

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

like image 170
sddamico Avatar answered Oct 22 '22 01:10

sddamico


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); 
like image 36
Raghunandan Avatar answered Oct 22 '22 00:10

Raghunandan