2014-12-21 60 views
0

我想使用for循環,字符串數組和可繪製文件夾中的png圖像更改圖像視圖的圖像。一個圖像應該休息5秒,然後下一個應該出現。這裏是我使用的代碼,並且它不能正常工作。圖像沒有變化。它每個循環等待5秒,但圖像不變。最後一個圖像被加載。請別人幫我.. 。想要使用ImageView和For循環制作幻燈片

private String [] array1 = {"card2c","card2d","card2h","card2s", 
            "card3c","card3d","card3h","card3s", 
            "card4c","card4d","card4h","card4s", 
            "card5c","card5d","card5h","card5s", 
            "card6c","card6d","card6h","card6s", 
            "card7c","card7d","card7h","card7s", 
            "card8c","card8d","card8h","card8s", 
            "card9c","card9d","card9h","card9s", 
            "card10c","card10d","card10h","card10s", 
            "cardjc","cardjd","cardjh","cardjs", 
            "cardqc","cardqd","cardqh","cardqs", 
            "cardkc","cardkd","cardkh","cardks", 
            "cardac","cardad","cardah","cardas",}; 

for(int j=0;j<52;j++) 
{ 
    int resID_temp1 = getResources().getIdentifier(array1[j] , "drawable", getPackageName()); 
    Drawable image_temp1 = getResources().getDrawable(resID_temp1); 
    Player1.setImageDrawable(image_temp1); // Player1 is the ImageView 

    try { 
    Thread.sleep(5000); 
     } 
    catch(InterruptedException ex) 
    { 
    Thread.currentThread().interrupt(); 
    } 

} 

試過定時器

(for(int j=0;j<52;j++) 
{ 
    timer.scheduleAtFixedRate(new TimerTask() { 
    @Override 
    public void run() { 
    //switch image here 
    int resID_temp1 = getResources().getIdentifier(array1[j] , "drawable", getPackageName()); 
    Drawable image_temp1 = getResources().getDrawable(resID_temp1); 
    Player1.setImageDrawable(image_temp1); 
    } 
}, 0, 5000); 

回答

0

嘗試使用定時器來代替:

//Declare final variable here 

Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() { 
@Override 
public void run() { 

    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      //Switch (declared final) image variable here 
     } 
    }); 

    } 
}, 0, 5000); 

這樣的事......我不是通過我的電腦。

概念:runOnUthread和最終變量可能也有興趣閱讀。最後是因爲否則變量不能在另一個線程上操作(實際上它真的只有另一個範圍在這裏)。 RunOnUiThread是因爲圖形組件只能在主UI線程上操作,儘管TimerTask在另一個單獨的線程上運行。

+0

對(INT J = 0;Ĵ<52; J ++){ timer.scheduleAtFixedRate(新的TimerTask(){ \t @覆蓋 \t公共無效的run(){ \t //切換圖像此處 \t INT resID_temp1 = getResources()則getIdentifier(數組1 [j]時, 「可拉伸」,getPackageName()); \t繪製對象image_temp1 = getResources()getDrawable(resID_temp1); \t Player1.setImageDrawable(image_temp1); \t} } ,0,5000); – SNT93

+0

我試過計時器,我已經更新了我的問題。但它不允許我在計時器中使用非最終變量.. – SNT93

+0

我會盡快在我回家的時候發表評論... – JohnyTex

0

根據您的代碼示例,您正在更改圖像資源,但隨後立即睡眠同一個線程,更改了圖像資源,這會阻止圖像並顯着改變圖像(尤其是如果這是UI線程因爲這會鎖定你的應用程序)。

你應該像JohnyTex建議的那樣做,並使用TimerTask來每5秒更換一次圖像,這不需要休眠,因此不會阻塞當前線程。