Android: use handler post.delayed twice

45.8k Views Asked by At

I would like to know if it's possible to use handler().postdelayed twice?

I mean, I want to create a button, that when clicked it change the color and stay in this state 1 second, then, after 1 second another button change the color.

I've created the following code:

In the onclicklistener:

btn3.setBackgroundColor(Color.WHITE);
  new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {

        checkAnswer();
        waitAnswer();
        btnRsp3.setBackgroundResource(R.drawable.selector); 
      }
    }, 1000);

CheckAnswer:

 public void CheckAnswer(){
      btn1.setBackgroundColor(Color.GREEN);

  new Handler().postDelayed(new Runnable() {
  @Override
  public void run() {
  }
}, 500);

btn1.setBackgroundResource(R.drawable.selector);
}

I think the problem is on CheckAnswer because it seems it doesn't stop in this postDelayed and step to the waitAnswer.

Thanks

2

There are 2 best solutions below

6
On

Why do you expect it to stop on postDelayed? postDelayed places your Runnable to the Handler Looper queue and returns. Since both handlers are created on the same looper, the second runnable is executed after the first one terminates (plus whatever left of the 500 ms delay)

UPDATE:

You need something like that

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        btn1.setBackgroundColor(Color.GREEN);
    }
}, 1000);
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        btn1.setBackgroundResource(R.drawable.selector);
    }
}, 2000);
0
On
new Handler().postDelayed(new Runnable() 
{
        @Override
        public void run() 
        {
            //Your Work
        }
  }, 1000);