OutOfMemory
如果您使用代码加载图像,您将面临异常。尝试使用以下方法正确加载图像。之后,您可以填充您的ListView
.
private static final int IMG_BUFFER_LEN = 16384;
// R.drawable.ic_default - default drawable resource, if we cannot load drawable from provided file
// R.dimen.list_icon_size - size in dp of ImageView inside of ListView (for example, 40dp)
private Drawable extractMediaIcon(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
if (options.outWidth < 0 || options.outHeight < 0 || (options.outWidth * options.outHeight == 0)) {
return context.getResources().getDrawable(R.drawable.ic_default);
}
final int targetHeight = dp2px((int) context.getResources().getDimension(R.dimen.list_icon_size));
final int targetWidth = targetHeight;
final boolean isScaleByHeight =
Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= IMG_BUFFER_LEN) {
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
final double sampleSize = isScaleByHeight
? options.outHeight / targetHeight
: options.outWidth / targetWidth;
options.inSampleSize =
(int) Math.pow(2d, Math.floor(
Math.log(sampleSize) / Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[IMG_BUFFER_LEN];
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap == null) {
return context.getResources().getDrawable(R.drawable.ic_default);
}
final double imageFactor = (double) bitmap.getWidth() / bitmap.getHeight();
final double targetFactor = (double) targetWidth / targetHeight;
bitmap = Bitmap.createScaledBitmap(
bitmap,
targetFactor > imageFactor ? bitmap.getWidth() * targetHeight / bitmap.getHeight() : targetWidth,
targetFactor > imageFactor ? targetHeight : bitmap.getHeight() * targetWidth / bitmap.getWidth(),
false);
return new BitmapDrawable(context.getResources(), bitmap);
}