【问题标题】:FragmentStatePagerAdapter memory issueFragmentStatePagerAdapter 内存问题
【发布时间】:2015-09-04 16:04:19
【问题描述】:

我正在使用 ViewPager 类和 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,但没有任何反应。

【问题讨论】:

    标签: android memory android-viewpager fragmentpageradapter fragmentstatepageradapter


    【解决方案1】:

    BitmapFactory.decodeResource(getResources(), position)创建的Bitmap必须通过调用Bitmap.recycle()手动释放

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

    【讨论】:

      【解决方案2】:

      我已经开始使用位图作为 ImageView 的输入。下面的代码运行良好。

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

      这在 onDestroy() 和 onDestroyView() 中:

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

      感谢您的帮助。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多