Custom ListView adapter and listview Adapter
Inherit the BaseAdapter class
Override the following four methods:
@ Override public int getCount () {return users. size () ;}@ Override public Object getItem (int position) {return users. get (position) ;}@ Override public long getItemId (int position) {return (User) getItem (position )). getId () ;}@ Override public View getView (int position, View convertView, ViewGroup parent) {if (convertView = null) {convertView = inflater. inflate (resouce, null);} // obtain the corresponding control TextView id = (TextView) convertView. findViewById (R. id. user_id); TextView name = (TextView) convertView. findViewById (R. id. user_name); TextView phone = (TextView) convertView. findViewById (R. id. user_phone); User user = (User) getItem (position); // bind the data id. setText (String. valueOf (user. getId (); name. setText (user. getName (); phone. setText (user. getPhone (); return convertView ;}
The above code implements a simple ListView adapter,
GetCount () gets the total number of items of the current data
GetItem () obtains objects that can obtain data based on POSITION.
GetItemId () obtains the ID of the data that can be obtained based on POSITION.
GetView () obtains the View object of the Item after the bound data according to POSITION and convertView.
The getView () method can be optimized in the following ways:
Public View getView (int position, View convertView, ViewGroup parent) {if (convertView = null) {convertView = inflater. inflate (resouce, null); // Cache control object viewControl views = new viewControl (); views. id = (TextView) convertView. findViewById (R. id. user_id); views. name = (TextView) convertView. findViewById (R. id. user_name); views. phone = (TextView) convertView. findViewById (R. id. user_phone); convertView. setTag (views);} viewControl views = (viewControl) convertView. getTag (); User user = (User) getItem (position); views. id. setText (String. valueOf (user. getId (); views. name. setText (user. getName (); views. phone. setText (user. getPhone (); return convertView;} private final class viewControl {public TextView id; public TextView name; public TextView phone ;}
Personal Understanding:
The adapter is actually the same as an adapter in a computer network. It is something that can be combined with a certain degree but cannot be directly connected together. Here, we assume the function of Binding data to controls.