2012-02-09 102 views
1

請大家幫忙,我是Android開發中的新手。我只是想動態地創建圖像動畫,換句話說,比如我想用它們創建3個圖像和動畫,然後在一些條件之後它應該變成4個圖像,5個圖像等等。 當我用3個Runnables分別創建3個圖像時,它工作正常,但是當我通過動態數組創建這3個Runnable時,它只是無所作爲。下面是代碼3分別可運行在Android中創建動畫

private Runnable run1= new Runnable() { 
public void run() { 
    if(t1) 
    { 
     LayoutParams params1=(LayoutParams) l1.getLayoutParams(); 
     params1.x=x1; 
     params1.y=y1; 
     l1.setLayoutParams(params1); 
     x2=r.nextInt(720-80)+80; 
     y2=r.nextInt(400-80)+80; 

    TranslateAnimation ta1 = new TranslateAnimation(0, x2-x1, 0, y2-y1); 
    ta1.setDuration(800); 
    ta1.setFillAfter(true); 
    l1.startAnimation(ta1); 
    x1=x2; 
    y1=y2; 

    handler.postDelayed(run1, 800); 

    } 
} 

與同爲RUN2和RUN3 它工作正常,但下面做什麼

for(j=0;j<c;j++)  
{ 
    run[j]=new Runnable() 
    { 
     public void run() { 
      if(t[j]) 

      { 

       params[j]=(LayoutParams) images[j].getLayoutParams(); 
       params[j].x=x1[j]; 
       params[j].y=y1[j]; 
       images[j].setLayoutParams(params[j]); 

       x2[j]=r.nextInt(720-80)+80; 
       y2[j]=r.nextInt(400-80)+80; 

       ta[j] = new TranslateAnimation(0, x2[j]-x1[j], 0, y2[j]-y1[j]); 
       ta[j].setDuration(200); 
       ta[j].setFillAfter(true); 
       images[j].startAnimation(ta[j]); 
       x1[j]=x2[j]; 
       y1[j]=y2[j]; 

       handler.postDelayed(run[j], 200); 
      } 
     } 

    }; 
for(j=0;j<c;j++)  
{ 
    this.runOnUiThread(run[j]); 
} 

如何解決這個問題,我的意思是如何創建的動畫與動態數量的圖像。

回答

1

首先,你應該檢查你的t [j]是否變成「真」,或者它總是保持假(我想你忘了把t [j]設置爲真)。 其次還有另一種動態創建圖像動畫的好方法。您應該將每個圖像作爲單獨類的對象提供,而不是使用普通類中的圖像,它應該提供2個屬性:圖像名稱和自己的布爾值t,用於決定此對象是否應具有動畫效果。此類應實現Runnable。然後你可以動態地創建這個類的對象數組,併爲每個對象運行animation.I是一個客觀的C開發人員,所以這裏是你可以輕鬆地轉移到Android的代碼。

class Single implement Runnable 
{ 
UIImageView* image; 
bool t; 
//method run{ 

//here you should create animation code 

} 
class common 
{ 
static int c=3; 
Single[] arrayOfObj=new Single[3]; 
//method onCreate 
{ 
//create objects of arrayOfObj with images that you want and then call run method for each object 
} 
} 
+0

謝謝你的回答。它對我非常有幫助! – hovo888s 2012-02-09 21:21:04