2011-07-05 36 views
1

我在模擬Frame Animation;我有這一切工作都有一個問題。 我有一個for循環,其中,在每次迭代中,它會延遲一段時間後更改ImageView的圖像。在循環中創建唯一的postDelayed Runnables

for(int i = 1; i <13; i++){ 
      if (stop== false){ 
       String imgName = "b"+ Integer.toString(i); 
        id = getResources().getIdentifier(imgName, "drawable", getPackageName()); 
       Handler handlerTimer = new Handler(); 
       handlerTimer.postDelayed(new Runnable(){ 
        public void run() { 
         view.setImageDrawable((getResources().getDrawable(id)));    
        }}, 300); 

      } 
     } 

問題是run()不會在每次迭代時刷新;它只能工作一次。

我該如何刷新或進行新的運行()?

我接受任何其他方式來做到這一點。

任何意見,將不勝感激。

回答

0

試試這個,如果它不工作,然後嘗試虐待別人的財產以後:

for(int i = 1; i <13; i++) 
{ 
    if (stop== false) 
    { 
     String imgName = "b"+ Integer.toString(i); 
     id = getResources().getIdentifier(imgName, "drawable", getPackageName()); 
     Handler handlerTimer = new Handler(); 
     handlerTimer.postDelayed(new Runnable(){ 
      public void run() { 
       view.setImageDrawable((getResources().getDrawable(id))); 
       view.invalidate();    
       }}, 300); 

    } 
} 

無效()應當引起你的觀點進行重新繪製,你應該得到預期的效果。希望這可以幫助!

這是主題例如:

public class Main implements Runnable 
{ 
    public Main() 
    { 
     Thread thread = new Thread(this); 
     thread.start(); 
     //new Thread starts at run() 
    } 

    public void run() 
    { 
     String imgName = "b"+ Integer.toString(i); 
     id = getResources().getIdentifier(imgName, "drawable", getPackageName()); 
     try 
     { 
      for(int i = 1; i <13&!stop; i++) 
      { 
       view.setImageDrawable((getResources().getDrawable(id))); 
       Thread.sleep(300); 
      } 
     }catch(Exception e){e.printStackTrace();} 
    } 

    public static void main(String args[]){new Main();} 
} 

,如果你需要別的可言,只是讓我知道!

+0

我不工作。我試着放置view.invalidate();在運行之外,它也沒有在那裏工作。 –

+0

您是否嘗試過使用線程而不是您使用的處理程序?如果你需要的話,我可以給你一個例子。 – gsfd

+0

是的,你能舉個例子嗎? –

1

第1步:定義Runnable爲您的活動的數據成員(或是其他地方,這個代碼駐留)

第2步:轉儲Handler,因爲你不需要它 - postDelayed()實現上View以及

第3步:創建一個具有postDelayed()調用一個輔助方法 - 我指的是方法foo()在這裏 - 並呼籲foo(),你有權不叫postDelayed()

聖ep#4:在的run()中,再次調用foo()以重新安排Runnable另一個延遲時間段