Android ViewPager OutOfMemory异常

标签 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));

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

最佳答案

内存不足异常

当使用可用平台资源无法满足内存请求时抛出。此类请求可能由正在运行的应用程序或 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)。这就是为什么有问题。缩小其尺寸(决议)。 您可以在 list 中添加 android:largeHeap="true" 。 希望这会有所帮助。

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

关于Android ViewPager OutOfMemory异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630993/

相关文章:

android - 在 Google Maps API v2 上绘制路线

ios - 图片下载保存导致内存压力

android - Android 上是否可以进行数据包转发?

android - 使手机在靠近特定位置时保持静音

android - 销毁以前的 ViewPager 项目以防止向后滚动

android - Glide和recyclerview,内存太大

java - Android URI 类 - 它的用途是什么?

Android:MotionLayout 不允许 child 展开并填满屏幕

android-viewpager - 如何在 Jetpack Compose Android 中单击按钮时 ScrollView 寻呼机(伴奏库)

android - 当我移动到相邻页面之外时,带有 TabLayout 的 ViewPager 不显示来自 recyclerview 的列表