FragmentStatePagerAdapter 内存问题

FragmentStatePagerAdapter memory issue

我正在使用 ViewPager class 和 FragmentStatePagerAdapter 适配器创建一个应用程序。我读到提到的适配器和 FragmentPagerAdapter 之间的区别在于后者将所有页面一次存储在内存中,而 FragmentStatePagerAdapter 在任何给定时间只有 3 个加载到内存中。

那么,问题来了。我有一个大约 50 页的 ViewPager。每个页面上都有一个片段,其中包含一个 ImageView 图像(以及一些其他元素)。滚动浏览大约 20 个不同的页面后,我通常会遇到内存不足错误。所以,我的问题是:我应该如何配置 FragmentStatePagerAdapter 在任何给定时间只在内存中加载大约 3 个页面?这是我的适配器的代码:

        mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {

        @Override
        public Fragment getItem(int position) {
            Song song = mSongs.get(position);
            return PlayFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            return mSongs.size();
        }

        @Override
        public void destroyItem(View collection, int position, Object o) {
            View view = (View)o;
            ((ViewPager) collection).removeView(view);
            view = null;
        }

        @Override
        public Object instantiateItem(View context, int position) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.findViewById(R.id.albumimage);
            imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), position));

            ((ViewPager) context).addView(imageView);

            return imageView;
        }

        });

destroyItem 和 instantiateItem 方法目前什么都不做。在从别人的问题中阅读了这个之后,我添加了它们。到目前为止,我的代码中是否有这两种方法都没有区别。

我读过其他与我的问题类似的问题,但在尝试自己解决问题但没有很好的结果后,我终于决定提出一个问题。

我尝试在 onDestroy() 中将 ImageView 设置为 null,但没有任何反应。

必须通过调用 Bitmap.recycle()

手动释放由 BitmapFactory.decodeResource(getResources(), position) 创建的

Bitmap

https://developer.android.com/training/displaying-bitmaps/manage-memory.html

我已经开始使用位图作为 ImageView 的输入。下面的代码工作正常。

albumimg = BitmapFactory.decodeFile(mSong.getImg());
mImg.setImageBitmap(albumimg);
mImg.setVisibility(View.VISIBLE);

在 onDestroy() 和 onDestroyView() 中:

if(albumimg != null) {`albumimg.recycle(); }`

感谢您的帮助。 :)