安卓加载图片过大而导致OOM内存溢出的解决方法(巨坑....)

如果图片太大会造成OOM内存溢出的错误,需要用Bitmap的压缩机制。

如果跳转的页面含有图片可能会导致跳转失败。

比如说我这里是一旦触发了某个按键,就修改该xml的图片和文字说明

则setImageResource应该改成这样

imageview.setImageBitmap(decodeSampledBitmapFromResource(getResources(),name[i], 100, 100));

同时后面加上以下说明:

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 options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        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;
    }

经调试,跳转页面不会崩溃,图片正常加载.


你可能感兴趣的:(android)