loading27
loading27

Reputation: 153

Android: use handler post.delayed twice

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

Upvotes: 14

Views: 45919

Answers (2)

Keshav Gera
Keshav Gera

Reputation: 11244

new Handler().postDelayed(new Runnable() 
{
        @Override
        public void run() 
        {
            //Your Work
        }
  }, 1000);

Upvotes: 1

msh
msh

Reputation: 2770

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

Upvotes: 21

Related Questions