Enes
Enes

Reputation: 89

How to use handler as a timer in android?

    Handler handler = new Handler();    
    if (v.getId() == R.id.play){    
       handler.postDelayed(new Runnable() {                    
       public void run() {
           play.setBackgroundResource(R.drawable.ilk);
       }
   }, 2000);    
       play.setText("Play");    
}

I want to set background first and then after 2 seconds later, code will continue next line which is play.setText("Play"); and goes like that. Instead of this, first text appears. 2 seconds later background changes.

Upvotes: 8

Views: 27488

Answers (2)

nshmura
nshmura

Reputation: 6000

Handler.postDelayed returns immediately. And next line is executed. After indicated milliseconds, the Runnable will be executed.

So your code should be like this:

void doFirstWork() {
    Handler handler = new Handler();

    if (v.getId() == R.id.play){

       handler.postDelayed(new Runnable() {
           public void run() {
               play.setText("Play");
               doNextWork();
           }
       }, 2000);

       play.setBackgroundResource(R.drawable.ilk);
    }
}

void doNextWork() {
    ...
}

Upvotes: 9

fluffyBatman
fluffyBatman

Reputation: 6704

Set the background first. After that set the text within Handler. As you've put delays at the end of postDelayed so it'll fire right after that stated delays or in your case after 2 sec.

if (v.getId() == R.id.play){
   play.setBackgroundResource(R.drawable.ilk);
   new Handler().postDelayed(new Runnable() {
       public void run() {
           play.setText("Play");
       }
   }, 2000);

}

Upvotes: 1

Related Questions