Jason
Jason

Reputation: 49

Strange thread behavior with onClickListener

I am trying to change the background of a button to 'pressed' for 1 second, then change that background back to 'default'. I created one Thread called sleeper that simply sleeps for 1 second. Below is the method I am using. The strange thing is, the buttons background doesn't change until the sleeper thread is done sleeping. I know threads are never guarenteed to start at any given time but since I am setting the background of the button before starting the Thread I figured this should work.

private void handleButtonPress(View button, int buttonPressedID,
        int buttonNormalID) {

    button.setBackgroundResource(buttonPressedID);
    Sleeper sleeper = new Sleeper();
    sleeper.start();
    try {
        sleeper.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

Thanks for having a look!

Upvotes: 0

Views: 390

Answers (1)

Philipp Jahoda
Philipp Jahoda

Reputation: 51421

Please simply use a Handler for that:

Handler h = new Handler();

h.postDelayed(new Runnable() {

    @Override
    public void run() {
        // do your delayed stuff here
    }
}, 1000); // execute the code inside run() after 1000ms

Upvotes: 2

Related Questions