我想以编程方式在ImageView
中添加一些linearLayout
。
但应用程序崩溃超过2个图像。它的错误是 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 :(得分:4)
使用较小的图像。
或者,使用BitmapFactory.Options
,特别是其inSampleSize
选项,将图片缩减为适合您屏幕尺寸的内容。
或者,使用可以为您处理inSampleSize
的第三方图片加载库,例如Picasso。
答案 1 :(得分:1)
通过使用这些方法,您可以根据使用情况调整图像大小。
public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth,int 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);
}
public static 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;
}