Android ViewPager OutOfMemory异常

时间:2016-01-06 10:37:12

标签: android android-viewpager out-of-memory android-imageview

我实现了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));

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

2 个答案:

答案 0 :(得分:2)

OutOfMemory Exception

在使用可用平台资源无法满足内存请求时抛出此异常。这样的请求可以由正在运行的应用程序或VM的内部功能进行。

  

您正在处理大型位图并在运行时加载所有这些位图   时间。您必须通过加载非常仔细地处理大位图   您需要的大小不是整个位图,而是一次   缩放。

问题在这里

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

imgFile 太大(大尺寸)。这就是为什么有问题。减小其大小(分辨率)。 您可以在清单中添加 android:largeHeap="true" 。 希望这会有所帮助。

  

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

答案 1 :(得分:0)

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