解决setBackgroundResource出现oom的问题

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);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值