1

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?

3 Answers3

2

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

Vivek Khandelwal
  • 7,829
  • 3
  • 25
  • 40
0

No it is setting Color but you are not able to see that. I will explain why you are not able to see.

The color is setting after 1 second. But you are starting new activity after 1 second, so you are not able to see the change of color. Actually the sleep paused the thread for given time.

To notice this effect, try below code.

       btn1.setOnClickListener(new View.OnClickListener() {             
            public void onClick(View v) {
                v.setBackgroundColor(Color.RED); 
                SystemClock.sleep(5000); // color will set after 5 seconds
            }
       });

I don't know how to overcome this problem. I answered just to inform this.

Yugandhar Babu
  • 10,311
  • 9
  • 42
  • 67
  • Thanks for your answer. I wanted to try a while loop that breaks when the color of the button is red, but I do not know how to check this. If tried to use the method getColor() of the class ColorDrawable, but eclipse says that this method does not exist. Do you know another way to check the background-color of a button? – user1186043 Feb 06 '12 at 12:36
0

You are setting the color on the same thread that is sleeping so your changes are not visible because the sleep command causes the UI to freeze.

You should set the color and then spawn a new thread that will wait 5 seconds before launching your other activity.

Kuffs
  • 35,581
  • 10
  • 79
  • 92