简体   繁体   中英

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.

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() {
    ...
}

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM