gpt4 book ai didi

Android ViewPager 内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:41 25 4
gpt4 key购买 nike

我需要在 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};

然后我创建适配器:

@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);

//

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

if (slide_image!= null) {
slide_image.recycle();
System.gc();
}

而且效果很好!但除了一件事:我有黑屏而不是第一张图片,经过几次翻转后,它被真实的屏幕所取代。所以我不知道如何处理这种内存泄漏

最佳答案

好吧,我终于解决了这个问题。我遇到了一个非常相似的案例,因为我看到了很多与同一问题相关的问题,所以我选择了这个问题,因为它还没有得到回答。PagerAdapter 不仅应该在超过 offLimitScreenPageLimit 时调用 destroyItem 方法,而且在发生屏幕旋转时也应该调用 destroyItem 方法,但它没有,所以它必须被迫这样做......要实现它,您只需在 Activity 的 onStoponDestroy 方法上将适配器设置为 null。

@Override protected void onDestroy(){
pager.setAdapter(null);
}

干杯!

关于Android ViewPager 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com