解决setBackgroundResource出现oom的问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Xs15073722800/article/details/51167476

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);
展开阅读全文

没有更多推荐了,返回首页