延迟android

时间:2017-08-13 09:16:42

标签: android

我试图让我的应用程序显示一系列图像,一秒钟后一秒钟。目前我的java看起来像这样:

    arrow1.setVisibility(View.VISIBLE);
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            arrow1.setVisibility(View.INVISIBLE);
            arrow2.setVisibility(View.VISIBLE);
        }
    }, 1000);
    handler.postDelayed(new Runnable() {
        public void run() {
            arrow2.setVisibility(View.INVISIBLE);
            arrow3.setVisibility(View.VISIBLE);
        }
    }, 1000);

我没有收到任何错误,但它也没有像我预期的那样工作。 Arrow2根本没有显示,应用程序直接从arrow1直接跳到arrow3。是我的第二个handler.postDelayed(新的Runnable()函数被覆盖了吗?在这种情况下我应该如何最好地延迟?

2 个答案:

答案 0 :(得分:1)

你可以这样试试,

private static final int TotalLoopCount = 2;

private int count  = 0;
private int mCurrentLoopCount = 0;

Handler handler = new Handler();  

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Your code

}


@Override
protected void onResume() {
    super.onResume();

    handler.postDelayed(runnable, 0);
}

@Override
protected void onPause() {
    super.onPause();
    handler.removeCallbacks(runnable);
}

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        arrow1.setVisibility(View.INVISIBLE);
        arrow2.setVisibility(View.INVISIBLE);
        arrow3.setVisibility(View.INVISIBLE);

        if(count == 0) {
            arrow1.setVisibility(View.VISIBLE);
        } else if(count == 1) {
            arrow2.setVisibility(View.VISIBLE);
        } else {
            arrow3.setVisibility(View.VISIBLE);
        }

        count++;

        if(count == 3) {
            count = 0;

            mCurrentLoopCount++;
        }

        if(mCurrentLoopCount < TotalLoopCount) {
            handler.postDelayed(runnable, 3000);
        }
    }
};

答案 1 :(得分:0)

您也可以使用CountDownTimer,如下所示。有关详细信息,请参阅official doc

为3张图片设置millisInFuture为countDownInterval * 3,并为图片之间的延迟设置countDownInterval

long countDownInterval = 1000; // 1sec interval
long millisInFuture = countDownInterval*10; // 10sec total time
new CountDownTimer(millisInFuture, countDownInterval) {

     public void onTick(long millisUntilFinished) {
        arrow1.setVisibility(millisUntilFinished < millisInFuture ?  View.VISIBLE:View.INVISIBLE);
        arrow2.setVisibility(millisUntilFinished > 0 ?  View.VISIBLE:View.INVISIBLE);
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();