一。利用PagerAdapter.instantiateItem,destroyItem 完成复用
1) 把destroyItem中获得的View控件,在instantiateItem中复用
省去重复创建View控件
private LinkedList<View> mViewCache = null;
@Override
public Object instantiateItem(ViewGroup container, int position) {
Log.e("test","instantiateItem " + position);
ViewHolder viewHolder = null;
View convertView = null;
if(mViewCache.size() == 0){
convertView = this.mLayoutInflater.inflate(R.layout.viewadapter_item_layout ,
null ,false);
TextView textView = (TextView)convertView.findViewById(R.id.view_pager_item_textview);
viewHolder = new ViewHolder();
viewHolder.textView = textView;
convertView.setTag(viewHolder);
}else {
convertView = mViewCache.removeFirst();
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.textView.setText(datas.get(position).title);
viewHolder.textView.setTextColor(Color.YELLOW);
viewHolder.textView.setBackgroundColor(Color.GRAY);
container.addView(convertView ,ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT );
return convertView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.e("test","destroyItem " + position);
View contentView = (View) object;
container.removeView(contentView);
this.mViewCache.add(contentView);
}
2)一种常见的情况,举例:有五个固定的控件要利用ViewPager显示
这种情况下,先创建好5个控件,并绑定ViewHolder,将ViewHolder放入List,
@Override
public Object instantiateItem(ViewGroup container, int position) {
//根据position计算出要取List中的哪个ViewHolder
viewhodler = list.get(index);
return viewhodler.itemView;
}