简体   繁体   English

如何在Android中将处理程序用作计时器?

[英]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"); 我想先设置背景,然后2秒后,代码将继续play.setText("Play");下一行play.setText("Play"); and goes like that. 像那样 Instead of this, first text appears. 取而代之的是,出现第一个文本。 2 seconds later background changes. 2秒后,背景发生变化。

Handler.postDelayed returns immediately. Handler.postDelayed立即返回。 And next line is executed. 然后执行下一行。 After indicated milliseconds, the Runnable will be executed. 在指定的毫秒后,将执行Runnable

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. 之后,在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. 由于您已将延迟放置在postDelayed的末尾,因此它将在所述延迟之后或在您的情况下2秒后立即触发。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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