Android ViewPager内存泄漏

Art*_*tas 4 android memory-leaks bitmap android-viewpager

我需要在Android中用5张幻灯片创建ViewPager,每张幻灯片都包含图像和文本。我有一个包含图像资源的数组:

  private static final int[] images = {R.drawable.tutorial_step_01, R.drawable.tutorial_step_02, R.drawable.tutorial_step_03, R.drawable.tutorial_step_04, R.drawable.tutorial_step_05, R.drawable.tutorial_step_06};
Run Code Online (Sandbox Code Playgroud)

然后我创建适配器:

@Override
    public Object instantiateItem(ViewGroup container, int position) {

        LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.tut_slide, null);
        TextView title = (TextView) tv.findViewById(R.id.tut_title);
        title.setText(getResources().getText(titles[position]));
        TextView content = (TextView) tv.findViewById(R.id.tut_content);
        ImageView image = (ImageView) tv.findViewById(R.id.tut_image);

        slide_image = BitmapFactory.decodeResource(getResources(), images[position]);
        image.setImageBitmap(slide_image);
        content.setText(getResources().getText(contents[position]));
        ((ViewPager) container).addView(tv, 0);
        return tv;
    }



    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((LinearLayout) object);
Run Code Online (Sandbox Code Playgroud)

//
}

问题是,事实是我不想在我选择另一个页面后android收集图像。因此,在10-15更改后,它会因OutOfMemory异常消失。然后我添加到initializung行

if (slide_image!= null) {
            slide_image.recycle();
            System.gc();
        }
Run Code Online (Sandbox Code Playgroud)

而且效果很好!但除了一件事:我有黑屏而不是第一个图像,几次翻转后,它被真实的图像代替。所以我不知道该怎么办

cae*_*eus 5

好吧,我终于解决了问题。我面对的是一个非常相似的案例,因为我已经看到太多与同一个问题相关的问题,所以我选择了这个问题,因为它尚未得到回答。本PagerAdapter应调用destroyItem方法不是只有当它超过了offLimitScreenPageLimit,而且当屏幕旋转时,但事实并非如此,所以它被迫这样做......去实现它,你只需要设置为null适配器活动的onStoponDestroy方法。

@Override protected void onDestroy(){
    pager.setAdapter(null);
}
Run Code Online (Sandbox Code Playgroud)

干杯!


alb*_*iro 0

该行为不应与内存泄漏有关。看起来它与您在 viewpager 更新生命周期中何时以及如何回收位图有关。尝试在初始化时的某个时刻手动调用 onPageSelected() 或 notificationDatasetChanged() 。

此解决方案可能无法完全解决问题,但请尝试一下。根据你的解释很难判断。