In fact, the reuse technology here is very common in the list, tableview in the iPhone also has related technologies, cell Reuse
Working principle:
- For each item in the list, listview requires the adapter to "give me a view" (getview ).
- A New View is returned and displayed.
What if we want to display hundreds of millions of projects? Create a new view for each project? No! This is impossible!
In fact, Android caches the view for you.
There is a recycler component in Android that works as follows:
- If you have 1 billion items, only visible items are in memory, and others are in recycler.
- Listview first requests a type1 view (getview) and then requests other visible projects. Convertview is null in getview.
- When Item1 is out of the screen and a new project is down from the screen, listview requests a type1 view. Convertview is not a null value. Its value is item1. You only need to set new data and return convertview. You do not need to create a new view.
See the following example.CodeIn getview, system. Out is used for output.
Public Class Multipleitemslist Extends Listactivity { Private Mycustomadapter madapter; @ override Public Void Oncreate (bundle savedinstancestate ){ Super . Oncreate (savedinstancestate); madapter = New Mycustomadapter (); For ( Int I = 0; I <50; I ++ ) {Madapter. additem ( "Item" + I);} setlistadapter (madapter );} Private Class Mycustomadapter Extends Baseadapter { Private Arraylist mdata = New Arraylist (); Private Layoutinflater minflater; Public Mycustomadapter () {minflater =(Layoutinflater) getsystemservice (context. layout_inflater_service );} Public Void Additem ( Final String item) {mdata. Add (item); policydatasetchanged () ;}@ override Public Int Getcount (){ Return Mdata. Size () ;}@ override Public String getitem ( Int Position ){ Return Mdata. Get (position) ;}@ override Public Long Getitemid ( Int Position ){ Return Position ;}@ override Public View getview ( Int Position, view convertview, viewgroup parent) {system. Out. println ( "Getview" + Position + "" +Convertview); viewholder holder = Null ; If (Convertview = Null ) {Convertview = Minflater. Inflate (R. layout. Item1, Null ); Holder = New Viewholder (); Holder. textview = (Textview) convertview. findviewbyid (R. Id. Text); convertview. settag (holder );} Else {Holder = (Viewholder) convertview. gettag ();} holder. textview. settext (mdata. Get (position )); Return Convertview ;}} Public Static Class Viewholder { Public Textview ;}}
Several items will not call functions that instantiate convertview after initialization. If (convertview = NULL) will not be executed, so data and corresponding listening should be set outside of it.
Note:
Convertview is the most out-of-the-box layout in R. layout. Item1.
Reference:
[Android] principle of getview in listview + how to place multiple items in listview