2013-10-21 59 views
-1

我有九張圖片需要在一個活動開始時加載,並且出現OutOfMemory異常問題。起初我直接在xml設置它的src中加載​​它們。因此,越來越java.lang.OutOfMemory後,我意識到,也許我需要更有效地加載照片,我創造了這個循環在活動開始時要執行:OutOfMemory問題加載幾張圖片

for(int i=0;i<9;i++){ 
     String background = "background"+(i+1); 
     int idDrawable = getResources().getIdentifier(background, "drawable", getPackageName()); 
     int idPicture = getResources().getIdentifier(background, "id", getPackageName()); 

     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeResource(getResources(), idDrawable, options); 

     options.inJustDecodeBounds = false; 
     ImageView image = (ImageView) findViewById(idPicture); 
     image.setImageBitmap(BitmapFactory.decodeResource(getResources(), idDrawable, options)); 
} 

但我仍然有同樣的問題,內存不足,關於我在做什麼錯誤的任何想法? googeling的

+0

負載圖像異步刪除此行 –

回答

2

使用下面的代碼。 此代碼

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeResource(getResources(), idDrawable, options); 

更改爲

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
options.inSampleSize = 4; 
BitmapFactory.decodeResource(getResources(), idDrawable, options); 

和在後臺線程

options.inJustDecodeBounds = false; 
+0

謝謝,這爲我工作,但不刪除'options.inJustDecodeBounds = false;'因爲否則圖像不加載。 – Monica