2011-10-24 21 views
0

我的Android應用程序基本上是一個簡單的,其中有一個列表視圖與40個列表項。並且每個這些項目點擊時導致一個圖像。所以有40個圖像。如何將圖像以最佳方式包含到Android項目中?

我總是可以的,當然地方在res /文件夾繪製這些圖像和從我的java文件直接引用它們,在這種情況下會出現硬編碼完成

img.setImageResource(R.drawable.day1); 
. 
. 
. 
img.setImageResource(R.drawable.day3); 
. 
. 

。 等

是否有(無論如何通過存儲圖像的名稱在一個xml例如)以編程方式從文件夾中檢索圖像名稱並顯示它們?

+0

你好看待這個問題 [1 ]:http://stackoverflow.com/questions/6776575/android-how-can-i-dynamically-load-drawables-pictures-names-not-known-until – Herry

回答

1
int resID = getResources().getIdentifier("day" + i, 
    "id", getPackageName()); 

其中i爲索引

img.setImageResource(resID); 
0

使用資源創建動態位​​圖對象。

ImageView image = (ImageView) findViewById(R.id.test_image); 
    Bitmap bMap = BitmapFactory.decodeFile("/sdcard/"+"test"+index+".png"); 
    image.setImageBitmap(bMap); 

使用的圖像的同名像,圖像1,圖像2 ... 呼叫使用循環或索引..

0

我會這樣做:

我會把圖像放在res/drawable文件夾中,就像你說的,但不會像你說的那樣調用它們;太多工作!嘗試創建一個數組的「影像」,充滿了一個for循環在其中添加在每個位置是這樣的:

for (i;i<x;i++) //Where x is the number of images you use 
    Images[i] = "R.drawable.day"+String.valueOf(i); 
    // Even you could try with: 
    // Images[i]="img.setImageResource(R.drawable.day"+String.valueOf(i)+")"; 

這樣,你只需要調用圖像[I]調用圖像「i」

我希望這可以幫助您:)

0

一種簡單的方式來做到這一點是這樣的: 您將您的圖像在res /繪製,名字全部採用一定的模式(例如:IMG1,IMG2,IMG3 ... ),然後使用以下名稱的模式動態加載它們:

String imageName =IMAGE_PATTERN+id; 
int imageResource = getResources().getIdentifier(imageName,null,getPackageName()); 
imageView.setImageDrawable(getResources().getDrawable(imageResource)); 

其中 IMAGE_PATTERN可能類似於不管你使用的命名文件:) 「圖像」 或 「IMG」 或

好運, Arkde

相關問題