2012-10-21 46 views
1

我正在製作一個程序,在同一ImageView中顯示圖像的不同部分。但它應該等待一段時間,大約500毫秒,在任何兩個圖像變化之間。 像這樣:如何在Android/Java for循環中等待迭代之間的特定時間?

for(int i=1; i<=4;i++){ 
    for(int j=1;j<=4;j++){ 
    //code to refresh the image. 
    // wait for 500 milliseconds before resuming the normal iteration 
    } 
} 

我嘗試使用下面的代碼:

for(int i=1; i<=4;i++){ 
    for(int j=1;j<=4;j++){ 
    //code to refresh the image. 
    Thread.sleep(500); 
    } 
} 

但是,這部分只顯示圖像的最後一段,不段。順便說一句,每個片段保存爲pic1,pic2,pic3 ..等(他們都是不同的圖像)。我想解決以下順序顯示出來:

  • PIC1
  • 等待500毫秒
  • PIC2
  • 等待500毫秒
  • PIC3
  • ...等等

謝謝你一噸

回答

3

如果這是在您的UI線程循環中,您應該使用AsyncTaskTimer來實現您的目標,以避免阻塞UI。

使用AsyncTask

class UpdateImages extends AsyncTask<Void, Integer, Boolean> { 
    @Override 
    protected void onPreExecute() { 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 
     // refresh the image here 
    } 

    @Override 
    protected Boolean doInBackground(Void... params) { 
     for(int i=0; i<4; i++) { 
      for(int j=0; j<4; j++) { 
       // NOTE: Cannot call UI methods directly here. 
       // Call them from onProgressUpdate. 
       publishProgress(i, j); 
       try { 
        Thread.sleep(500); 
       } catch(InterruptedException) { 
        return false; 
       } 
      } 
     } 
     return true; 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
    } 
} 

然後就叫

new UpdateImages().execute(); 

當你要開始這個任務。通過這種方式使用AsyncTask可以避免阻止您的用戶界面,並且仍然可以讓您按計劃執行任何操作。

+0

請注意'Thread.sleep'會拋出'InterruptedException'。你應該用try/catch塊代碼來包圍這個句子。 –

+0

好的。我知道我忘了一些東西:) – nneonneo

+0

有一個問題,我應該在我的activity.java類中包含這個類,還是在同一個包中聲明它? – Gaurav

相關問題