ViewPager源碼分析(二) Page的複用

一。利用PagerAdapter.instantiateItem,destroyItem 完成複用ide

1) 把destroyItem中得到的View控件,在instantiateItem中複用
省去重複建立View控件this

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,code

@Override  
    public Object instantiateItem(ViewGroup container, int position) {  
        //根據position計算出要取List中的哪一個ViewHolder
        viewhodler = list.get(index);
        return viewhodler.itemView;
    }
相關文章
相關標籤/搜索