BenH
BenH

Reputation: 2120

In Android, how do I change the color of a button, pause for a few seconds, then change it again?

Here is my code:

public class TestActivity extends Activity {    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start();
    }

    private void start() {
        setContentView(R.layout.main);

        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);

        Button button = new Button(this);

        layout.addView(button);

        button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x0000FF00));  // green
        button.invalidate(); 

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x000000FF));  // blue
        button.invalidate(); 
    }
}

This just displays a blue button after 3 seconds; it never shows it as green.

I think that if my brain worked properly, I could figure out the answer from one of these posts:

Why isn't view.invalidate immediately redrawing the screen in my android game

How to force a view to redraw immediately before the next line of code is executed

How to force an entire layout View refresh?

Upvotes: 4

Views: 947

Answers (2)

Jason Sankey
Jason Sankey

Reputation: 2338

You should not sleep on the UI thread, as this will hang your interface. Instead, after initially setting the colour to green, you could create a Handler (on the UI thread, so it will use that thread to handle messages), then use Handler.postDelayed to send a message that will be handled in 3 seconds. In the Runnable you pass to postDelayed you can set the colour to blue.

Upvotes: 2

Rowan Freeman
Rowan Freeman

Reputation: 16348

You're sleeping the main UI thread virtually instantly after setting the colour. This means that the thread is locked up before it gets a chance to do redrawing.

One solution to this is to use threads. Set the background colour, then use another thread to sleep which on completion calls the main (UI) thread to change the colour again.

You can try looking up AsyncTask or Threading.

Upvotes: 1

Related Questions