Android: use handler post.delayed twice

loading27 picture loading27 · Aug 17, 2013 · Viewed 43.2k times · Source

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

Answer

msh picture msh · Aug 17, 2013

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);