2014-11-25 129 views
-1

我想以编程方式在linearLayout中添加几个ImageView。 但应用程序崩溃超过2个图像。它的错误是OutOfMemoryError。以编程方式添加imageView时OutOfMemoryError

String[] titleImages={"a","b","c","d","e","f","g"}; 
for (String title : titleImages){ 

     InputStream inputStream = context.getAssets() 
       .open("titles"+"/"+title); 
     Drawable drawable = Drawable.createFromStream(inputStream, null); 
     inputStream.close(); 

     ImageView imageView = new ImageView(_context); 
     imageView.setScaleType(ScaleType.FIT_XY); 
      imageView.setImageDrawable(drawable); 
     //more imageView set properties 
     LinearLayout shelf=findViewById(R.id.shelf); 
     //shelf is a LinearLayout 
     shelf.addView(imageView); 
    } 
+0

使用尝试捕捉。处理内存不足 – 2014-11-25 12:59:02

+0

@AshwinSAshok这是一个错误,没有例外。在大多数情况下,不应该捕获“Error”的子类,而其中的“OutOfMemoryError”。 – aga 2014-11-25 13:01:12

回答

4

使用较小的图像。

或者,使用BitmapFactory.Options,特别是其inSampleSize选项,将图像缩减采样到更适合您的屏幕尺寸的东西。

或者,使用第三方图像加载库,如Picasso,可以为您处理inSampleSize

+1

与位图/图像相关的任何OutOfMemoryException应该不再被回答:) – 2014-11-25 13:37:34

1

通过使用这些方法,您可以根据您的使用调整图像的大小。

公共静态位图decodeSampledBitmapFromResource(资源RES,INT渣油, INT reqWidth,诠释reqHeight){

// First decode with inJustDecodeBounds=true to check dimensions 
final BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeResource(res, resId, options); 

// Calculate inSampleSize 
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

// Decode bitmap with inSampleSize set 
options.inJustDecodeBounds = false; 
return BitmapFactory.decodeResource(res, resId, options); 

}

公共静态INT calculateInSampleSize( BitmapFactory.Options选项,INT reqWidth,INT reqHeight){ //图像的原始高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) { 

    final int halfHeight = height/2; 
    final int halfWidth = width/2; 

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
    // height and width larger than the requested height and width. 
    while ((halfHeight/inSampleSize) > reqHeight 
      && (halfWidth/inSampleSize) > reqWidth) { 
     inSampleSize *= 2; 
    } 
} 

return inSampleSize; 

}

相关问题