0

I'm trying to create a simon says game so to let the user know which buttons to hit I decided I wanted to do something like upon a button click change background wait a second then change it back it doesn't work right though the button waits 1 second to click but the drawable doesn't change

What I have looks something like this

view.setBackgroundResource(R.drawable.black);

try {
      TimeUnit.SECONDS.sleep(5);           
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

view.setBackgroundResource(R.drawable.green);

4 Answers4

3

You can achieve this using Handler. In my example, I set a 5sec delay after which I change the background color via view.setBackgroundResource(R.drawable.green);.

 Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
          view.setBackgroundResource(R.drawable.green);
      }
    }, 5000);
robinCTS
  • 5,568
  • 14
  • 28
  • 37
Mahesh Gawhane
  • 313
  • 3
  • 19
1

You can try CountDownTimer.

// You can change millisInFuture and countDownInterval according to your need.
long millisInFuture = 5000;
long countDownInterval = 1000;

new CountDownTimer(millisInFuture, countDownInterval) {
     @Override
     public void onTick(long l) {

     }

     @Override
     public void onFinish() {
         // Change your background color here
         view.setBackgroundResource(R.drawable.green);
     }
}.start();
Andy Developer
  • 3,001
  • 1
  • 18
  • 39
1

you can use new Handler()try something below like this.

view.setBackgroundResource(R.drawable.black);

     new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
          view.setBackgroundResource(R.drawable.green);
      }
    }, 5000);
ItamarG3
  • 3,974
  • 6
  • 29
  • 42
UserSharma
  • 442
  • 5
  • 20
0

Try changing the view background in runOnUiThread and invalidating the view.

Aditi
  • 389
  • 4
  • 13