在写PagerAdapter的时候,需要重写instantiateItem(ViewGroup container ,int position)
此方法中,将需要加载的View,添加到container中。
PagerAdapter不能直接使用像ListView那样的ViewHolder,来实现View的复用。
所以,如果每次加载,都要新建一个View出来就会很占用内存。
如果你的View都是一样的,比如都是ImageView,那么就可以使用一个List将回收的View存起来
再次加载的时候,优先从回收List中加载,不必再去new.
大致的逻辑如下:
private LinkedList < View> recycledViews = new LinkedList <View > ();
public Object instantiateItem( ViewGroup container , int position ) {
// TODO Auto-generated method stub
CustomImage imageView = null;
if ( debug )
Log. e (TAG , "PagerAdapter : instantiateItem"+ "position is "+ String .valueOf (position )+ "ChildCount is:" +container .getChildCount ());
if ( recycledViews != null && recycledViews. size() >0 ) {
imageView = ( CustomImage) recycledViews .getFirst ();
recycledViews .removeFirst ();
} else {
imageView = new CustomImage (mContext );
}
imageView .setImageResource (resids .get (position ));
container .addView (imageView );
return imageView;
}
@Override
public void destroyItem( ViewGroup container , int position , Object object ) {
// TODO Auto-generated method stub
if ( debug )
Log. e (TAG , "PagerAdapter : destroyItem"+ "position is"+ String .valueOf (position )+ "ChildCount is:" +container .getChildCount ());
((ViewGroup ) container ). removeView ((View ) object );
if ( object != null) {
recycledViews .addLast ((View )object );
}
}
上面的CustomView是我自定义的一个ImageView,可以用任意的View代替。效果一样的。