The code is as follows:
public class Myviewpageradapter extends Pageradapter {//Display data 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", "destroy Item "+ 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; }}
first, we need to understand the callback mechanism of each method of Viewpager's adapter. Here are two main ways to see: Instantiateitem () andDestroyitem (). The Instantiateitem () method is called when sliding to a new viewitem, and Destroyitem () is called when the user slides to the 3rd ViewItem. At this point, this method is called to reclaim the first ViewItem, and then the Instantiateitem () method is called to instantiate the 3rd ViewItem. The ability to play log in the various callback methods of adapter to see when this method is called. Using the mechanism described above, it is possible to reclaim the view that will be removed when Destroyitem (), and then use the view repeatedly at Instantiateitme (). In this way, only 3 instances of Viewholder are present. That is currently displayed. There is also the previous item and the next item.
Re-use of view in Viewpager