您的位置:首页 > 其它

解决setBackgroundResource出现oom的问题

2016-04-16 13:01 477 查看
setBackgroundResource加载图片的额时候。会出现错误。

private final int[] imageIds = { R.mipmap.a, R.mipmap.b, R.mipmap.c,

R.mipmap.d, R.mipmap.e };

ImageView image = new ImageView(this);

image.setBackgroundResource(imageIds[i]);//这儿会出现OOM错误。

imageList.add(image);

错误如下:java.lang.OutOfMemoryError: Failed to allocate a 8487512 byte allocation with 4194304 free bytes and 6MB until OOM

Throwing OutOfMemoryError “Failed to allocate a 8487512 byte allocation with 4194304 free bytes and 6MB until OOM”

allocation failed for scaled bitmap

at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)

04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)

04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)

04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:467)

04-16 04:42:19.465 2703-2703/? E/AndroidRuntime: at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:497)

出现问题的原因是;图片加载过大,建议大家使用库来完成图片的加载,setBackgroundResource的时候要转换为bitmap,要求的内存太多,当前系统无法满足

网上很多教程,百度 图片放缩。

下面附加一个不带库的。

//初始化图片资源

ImageView image = new ImageView(this);
//            image.setBackgroundResource(imageIds[i]);
//////////////
BitmapFactory.Options opt = new BitmapFactory.Options();

opt.inPreferredConfig = Bitmap.Config.RGB_565;

opt.inPurgeable = true;

opt.inInputShareable = true;

InputStream is = getResources().openRawResource(

imageIds[i] );

Bitmap bm = BitmapFactory.decodeStream(is, null, opt);

BitmapDrawable bd = new BitmapDrawable(getResources(), bm);

image.setBackgroundDrawable(bd);

//          BitmapFactory.decodeResource(getResources(),imageIds)
imageList.add(image);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: