我使用带有ViewPager
的片段和自定义PagerAdapter
来显示位图图片。
位图在BitmapFactory
方法中按需加载instantiateItem
,并在destroyItem
中回收。因此,当向左和向右滑动时,只有3个位图在内存中,而旧的位图则被破坏。
离开片段时,不会调用destroyItem
。我是否必须手动回收剩余的项目以避免位图泄露?或者,当ViewPager
和适配器被销毁时,它们是否会自动进行垃圾回收?
更新 因为SilentKnight需要一些代码,所以这里是适配器的相关部分:
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
Log.wtf(LOGTAG, "Instantiate " + position);
final ImageItem imageItem = new ImageItem();
imageItem.imagePath = imagePaths.get(position);
imageItem.bitmap = BitmapFactory.decodeFile(imageItem.imagePath);
final View viewLayout = inflater.inflate(R.layout.media_image_item, container, false);
final ImageView imageView = (ImageView) viewLayout.findViewById(R.id.imageView);
imageView.setImageBitmap(imageItem.bitmap);
imageItem.itemView = viewLayout;
container.addView(viewLayout);
return imageItem;
}
@Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
Log.wtf(LOGTAG, "Destroy " + position);
final ImageItem imageItem = (ImageItem) object;
container.removeView(imageItem.itemView);
imageItem.bitmap.recycle();
}
ImageItem
只是简单的持有人:
private class ImageItem {
private View itemView;
private Bitmap bitmap;
private String imagePath;
}