尝试多次延迟Java

时间:2019-02-15 17:06:35

标签: java android animation timing

需要制作一个动画,先休眠1000次,然后再休眠1000次,依此类推,而是先休眠整个时间,然后一次播放所有动画。不知道我在做什么。

尝试过的计时器,在踩踏之前运行动画,并使用While循环而不是For。

private void playLaunchAnimation()
{

final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);

    for(int i=0; i < buttons.size();i++)
    {
        try {
            Thread.sleep(1000);
            buttons.get(i).startAnimation(animation);

        } catch (Exception e){
        /*
main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.

        */

        }

    }

}

3 个答案:

答案 0 :(得分:0)

听起来您正在从用户界面线程中调用Thread.Sleep。这最终将导致整个用户界面在睡眠期间冻结。您真正想要的是从后台线程启动睡眠。

例如:

AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      for(int i=0; i < buttons.size();i++)
      {
          try {
              Thread.sleep(1000);
              activity.runOnUiThread(new Runnable() {
                  buttons.get(i).startAnimation(animation);
              });
          } catch (Exception e){}
      }
});

使用发布延迟的另一种方法:

new android.os.Handler().postDelayed(
    new Runnable() {
        public void run() {
            buttons.get(i).startAnimation(animation);
            new android.os.Handler().postDelayed(this, 1000);
        }
    }, 
1000);

答案 1 :(得分:0)

嗨,请确保此代码对您有帮助

public static void main(String[] args) throws Exception {

        for(int i=0; i < 10;i++) {
            try {
                Thread.sleep(1000);
                System.out.println(i);
                if(i==9) {
                    i=0;
                }

            } catch (Exception e){
                System.out.println("error");
            }

        }

    }

答案 2 :(得分:0)

(答案假定Android在OP中并不完全清楚。)

这在某种程度上是一种懒惰的方式-但也许会让您思考。它会 让处理程序调用下一个处理程序会更有趣,因此仅声明一个处理程序-但这会需要更多的工作。

private void playLaunchAnimation() {

    final Animation animation = AnimationUtils.loadAnimation(this, R.anim.fadein);

    for(int i=0; i < buttons.size();i++)
    {
        // Create a handler on the UI thread to execute after a delay.
        // The delay is a function of loop index.
        // 
        // It may be necessary to declare buttons final - but your
        // OP did not list where it is defined.

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
              buttons.get(i).startAnimation(animation);
            }
        }, ((i+1)*1000));

    }

}

参考文献:

How to call a method after a delay in Android

Android basics: running code in the UI thread