ViewPager中View的複用
程式碼如下:
public class MyViewPagerAdapter extends PagerAdapter { //顯示的資料 private List<DataBean> datas = null; private LinkedList<View> mViewCache = null; private Context mContext ; private LayoutInflater mLayoutInflater = null; public MyViewPagerAdapter(List<DataBean> datas, Context context) { super(); this.datas = datas; this.mContext = context ; this.mLayoutInflater = LayoutInflater.from(mContext) ; this.mViewCache = new LinkedList<>(); } @Override public int getCount() { Log.e("test","getCount "); return this.datas.size(); } @Override public int getItemPosition(Object object) { Log.e("test","getItemPosition "); return super.getItemPosition(object); } @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); } @Override public boolean isViewFromObject(View view, Object o) { Log.e("test","isViewFromObject "); return view == o; } public final class ViewHolder{ public TextView textView ; } }
首先需要了解ViewPager的Adapter各個方法的回撥機制。 這裡主要看兩個方法:instantiateItem()和destroyItem()。 instantiateItem()方法,是在滑動到一個新的ViewItem的時候被呼叫的,而destroyItem()是在當用戶滑到第3個ViewItem的時候被呼叫,在這個時候會先呼叫這個方法來回收第一個ViewItem,然後在呼叫instantiateItem()方法來例項化第3個ViewItem。可以在adapter的各個回撥方法中打出log來看這個方法被呼叫的時機。 利用上面所說的機制,就可以在destroyItem()的時候將要被remove掉的view回收起來,然後在instantiateItme()的時候重複利用這個view。這樣,就只會有3個ViewHolder例項存在。即當前顯示的,還有上一個Item和下一個Item。