Search code examples
androidbuttonsleepsystem-clock

Changing the background of a button and sleep


I want to change the background of a button to red and then wait for one second before calling another activity.

This is my code:

btn1.setBackgroundColor(Color.RED);
SystemClock.sleep(1000);
startActivity(intent);

The problem is that the application sleeps for one second and starts the activity, but the color of the button does not change. How can I fix this?


Solution

  • When you use SystemClock.sleep(1000);

    your Main thread which handles the Looper gets Sleep.

    And then when its returns it first change the color and then start the Activity. which are done one after the other without delay, so u are not able to see the changed color.

    Use Handler postDelayed which will help u to run the activity after the delay u need and which also not block the Main Looper Thread by sleep