Android ViewPager OutOfMemory 异常

Android ViewPager OutOfMemory Exception

我实现了 ViewPager,但我在 instantiateItem 方法中遇到了 OutOfMemory 异常:

@Override
    public Object instantiateItem(ViewGroup container, int position) {
        Context context = QPhotoGallery.this;
        mImageViewForPager = new ImageView(context);
        mImageViewForPager.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

        mImageForView = mImages.get(position);

        File imgFile = new  File(mImageForView.getPath());
        if (imgFile.exists()) {
            mImageViewForPager.setImageURI(Uri.fromFile(imgFile));
            if (mImageForView.getOrientation() == ExifInterface.ORIENTATION_ROTATE_90)
                mImageViewForPager.setRotation(90);
            if (mImageForView.getOrientation() == ExifInterface.ORIENTATION_ROTATE_180)
                mImageViewForPager.setRotation(180);
            if (mImageForView.getOrientation() == ExifInterface.ORIENTATION_ROTATE_270)
                mImageViewForPager.setRotation(270);
        }

...
}

这一行:

mImageViewForPager.setImageURI(Uri.fromFile(imgFile));

导致异常。有人有想法吗?

内存不足异常

当使用可用平台资源无法满足内存请求时抛出。 运行 应用程序或 VM 的内部函数都可以发出此类请求。

You are dealing with large bitmaps and loading all of them at run time. You have to deal very carefully with large bitmaps by loading the size that you need not the whole bitmap at once and then do scaling.

问题在这里

mImageViewForPager.setImageURI(Uri.fromFile(imgFile));

imgFile 太大 (Big Size) 。这就是为什么有问题。减小它的尺寸(Resolutions) 。 您可以在清单中添加 android:largeHeap="true" 。 希望这有帮助。

https://developer.android.com/intl/es/training/displaying-bitmaps/index.html

将图像加载到内存中时,请记住您应该始终考虑将其缩小,查看Android官方教程-Loading Large Bitmaps Efficiently