0

The main motive is very basic: pause the loop makes the UI change and pause again makes the UI change to dynamically created View(s) and manually assigned id(s) to views.

Thread.sleep() is not working

for(int i=0;i<n;i++){
Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    @SuppressLint("ResourceType") Button mButton = (Button) findViewById(i);
                                    mButton.setBackgroundColor(Color.parseColor("#ABCDEF"));
                                }
                            }, 1000);
}

Using Handler is also not working. When Handler is put inside a loop, it takes the last value of loop always i.e. n-1 always.

null_override
  • 467
  • 3
  • 10
  • 30
Shivam Anand
  • 952
  • 1
  • 10
  • 21
  • UI related changes must be done on UI thread. – Amrish Kakadiya Sep 10 '20 at 07:11
  • It isn't clear what you're trying to do here. Are you trying to update the background colours of a group off buttons sequentially, after a delay of one second each? In addition, why aren't you accessing your button with a resource id? – PPartisan Sep 10 '20 at 11:48

2 Answers2

0

i think you have to clear the question and give a more details of what you mean by sleep not working >>> do you use it in this way?

Thread.sleep(1000); // do nothing for 1000 miliseconds

and you can try

Thread.wait(sleeptime);//Sample Thread.wait(1000); 1 second sleep

but in general delay the main thread in android is not something good reference java-delay-wait

Sideeg MoHammed
  • 375
  • 2
  • 10
0
  • You can delay UI change in Android using Handler. Handler starts a new Thread and it accepts time after which it executes.
  • To change UI at repeated intervals of time, set timeInMillisecons as multiples of itself.

    Handler handler = new Handler(Looper.myLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                    /**
                     * Change UI here
                     */
                    }
                }, timeInMillisecons);
Shivam Anand
  • 952
  • 1
  • 10
  • 21