2017-08-13 51 views
2

我試圖讓我的應用程序顯示一個圖像序列,1秒鐘後。目前我的Java是這樣的:有延遲的動作序列android

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

我沒有得到任何錯誤,但它也沒有我預期工作。箭頭2根本不顯示,應用程序從箭頭1直接向箭頭3稍微延遲。是我的第二handler.postDelayed(新的Runnable()函數被重寫?我應該如何去最好的關於此方案具有延遲?

回答

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); 
     } 
    } 
}; 
+0

我無法從內部類中訪問變量處理程序,而無需聲明它最終 – Roonil

+0

我更新了我的答案看看。 –

+0

現在就開始吧!在完成了幾次之後,我如何才能讓它停止? – Roonil

0

您還可以使用CountDownTimer如下圖所示。詳情請參閱official doc

設置millisInFuture到countDownInterval * 3 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();