如何正确地在两次调用同一函数之间等待一段时间?

时间:2019-01-12 09:59:29

标签: java android wait

因此,我一直试图在每次我想使用“ setText”编写新消息之间的两秒钟的小暂停。

public void startNewGame() throws InterruptedException {

            welcomeMessage("Welcome.");

            if (!seenTutorial) {
                seenTutorial = true;
                welcomeMessage("This is the first message.");
                welcomeMessage("This is the second message.");
                welcomeMessage("This is the third message.");
            }
        }


      public void welcomeMessage(String message) throws InterruptedException {

            welcomeText.setAlpha(0f);
            welcomeText.setText(message);
            welcomeText.animate().setDuration(2000).alpha(1.0f);
        }

我尝试过wait(2000),但是程序崩溃了。

还尝试将welcomeMessage方法的内容包含在以下内容中:

    public void welcomeMessage(String message) throws InterruptedException {
     Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                         welcomeText.setAlpha(0f);
                         welcomeText.setText(message);
                         welcomeText.animate().setDuration(2000).alpha(1.0f);
                    }
                }, 2000);   //2 seconds
}

这样,只有最后一条消息“这是第三条消息”。会出现。 我在做什么错了?

3 个答案:

答案 0 :(得分:0)

似乎正在发生的情况是,Handler在创建后两秒钟被触发,而不是在前一个处理程序完成操作后两秒钟被触发。

您可能希望对每个欢迎消息分别设置延迟时间。这意味着第一条消息需要2秒,第二条消息需要4秒,第三条消息需要6秒。

答案 1 :(得分:0)

welcomeMessage方法中,每次发布计划在其上创建Handler的同一线程上延迟运行的r Runnable时,都会创建新的Handler

那么发生的是这三个可运行对象都将在运行2000毫秒后运行,因此这就是为什么您仅看到第三个可运行对象的效果的原因。是的,您可以为它们安排不同的延迟(因此它们之间会有时间间隔),即2000、4000、6000。

 public void welcomeMessage(String message, int delay) throws InterruptedException {
     Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                         welcomeText.setAlpha(0f);
                         welcomeText.setText(message);
                         welcomeText.animate().setDuration(2000).alpha(1.0f);
                    }
                }, delay);   
}

showMessage("hello", 2000);
showMessage("lets play the game", 4000);

答案 2 :(得分:0)

而不是调用方法三遍并将其放入处理程序中,请尝试

将消息存储在字符串数组中

    String[] messages = {"This is the first message","This is the second 
                           message","This is the third message"}

    public void welcomeMessage() throws InterruptedException {
         int i=0;
while(i<messages.size()){
         Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                             welcomeText.setAlpha(0f);
                             welcomeText.setText(message[i]);
                             welcomeText.animate().setDuration(2000).alpha(1.0f);
                        }
                    }, 2000);   //2 seconds
                  i=i+1;
    }

}