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?

有帮助吗?

解决方案

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

其他提示

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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top