The use and optimization of-android-baseadapter in mu ke Net-study notes
What is a data adapter
A data adapter is a bridge between a data source and a view that establishes an adaptation relationship between the two. The source of the data is various, but the view can display the format is a certain requirement, the data adapter is a variety of data sources into the view can be displayed data format.
Advantages:
The source of data and the display of data are decoupled to reduce the coupling of the program and improve the scalability.
Baseadapter is the most versatile adapter in Android's various adapters.
Baseadapter Basic Structure
- public int GetCount (): The number of data in the data set in the adapter, that is, the number of data that the ListView needs to display
- Public Object getItem (int position): Gets the data item that corresponds to the specified index in the data set
- public long getitemid (int position): Gets the ID corresponding to the specified row
- Public View GetView (int position, View Convertview, viewgroup parent): Gets the display of each item
When using baseadapter, we need to create a class to inherit Baseadapter, and Eclipse will remind us to implement the above four methods, when we set our own adapter to the ListView, The above four methods are called inside the ListView.
Baseadapter's Tease
This is the basic form used by Baseadapter, and here is the implementation step:
- New Android Engineering Mybaseadapter, preparing the interface layout
Modify the Activity_main and change the TextView to a ListView, as follows:
<relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:paddingbottom="@dimen/activity_vertical_margin"android:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"tools:context="Com.mybaseadapter.MainActivity"> <listview android:id="@+id/lv_main"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:text="@string/hello_world"/></relativelayout>
Create layout layouts for individual data items: Item.xml
<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Match_parent"android:layout_height="Wrap_content" android:orientation="vertical" > <imageview android:id
= "@+id/iv_image" android:layout_width = "64DP" android:layout_height = "64DP" android:src =" @drawable/ic_launcher "/> <textview android:id = "@+id/tv_title" android:layout_width = "match_parent" android:layout_height = "30DP" android:layout_torightof =< Span class= "Hljs-value" > "@id/iv_image" android:text =" Title " android:gravity =" center " android:textsize =" 25sp "/> <textview android:id = "@+id/tv_content" android:layout_width = "match_parent" android:layout_height = "30DP" android:layout_torightof =< Span class= "Hljs-value" > "@id/iv_image" android:layout_below = "@id/tv_title" android:text =" Content " android:gravity =" Center_vertical " android:textsize =" 20SP "
/> </relativelayout>
- Create a Bean object with three attributes corresponding to the above item, which encapsulates a single piece of data
package com.mybaseadapter;publicclass ItemBean {publicintpublicpublicpublicItemBean(int itemImageResid, String itemTitle, String itemContent) { super(); this.itemImageResid = itemImageResid; this.itemTitle = itemTitle; this.itemContent = itemContent; }}
- Create Myadapter inheritance Baseadapter to implement the four methods we need to implement
PackageCom.mybaseadapter;ImportJava.util.List;ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView; Public class myadapter extends baseadapter{ PrivateList<itembean> mlist;PrivateLayoutinflater Minflater;/** * Associated data source and data adapter * @param list */ Public Myadapter(context context, list<itembean> List) {mlist = list; Minflater = Layoutinflater.from (context); }@Override Public int GetCount() {//TODO auto-generated method stub returnMlist.size (); }@Override PublicObjectGetItem(intPosition) {//TODO auto-generated method stub returnMlist.get (position); }@Override Public Long Getitemid(intPosition) {//TODO auto-generated method stub returnPosition//Corresponding index entry}@Override PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {//TODO auto-generated method stub //Returns the display of each item /********* tease Style **************/ /** * Ignoring convertview and parent, without considering the feeling of the ListView, not using the caching mechanism * each time is to create a new view, and in view to find the appropriate control to set the corresponding value, * completely useless to the cache mechanism, the resources caused by the Great Waste * * //CREATE VIEWView view = This. Minflater.inflate (R.layout.item,NULL); ImageView image = (ImageView) View.findviewbyid (r.id.iv_image); TextView title = (TextView) View.findviewbyid (r.id.tv_title); TextView content = (TextView) View.findviewbyid (r.id.tv_title);//Associated dataImage.setimageresource (Mlist.get (position). Itemimageresid); Title.settext (Mlist.get (position). Itemtitle); Content.settext (Mlist.get (position). itemcontent);returnView }}
- Create test data, connect the ListView and test data with an adapter
PackageCom.mybaseadapter;ImportJava.util.ArrayList;ImportJava.util.List;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.widget.ListView; Public class mainactivity extends actionbaractivity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Create test DataList<itembean> itembeanlist =NewArraylist<itembean> (); for(inti =0; I < -; i++) {Itembeanlist.add (NewItembean (R.drawable.ic_launcher,"title"+ I,"Content"+ i)); } ListView LV = (listview) Findviewbyid (R.id.lv_main); Myadapter adapter =NewMyadapter ( This, itembeanlist); Lv.setadapter (adapter); }}
- Summarize
This is called the pattern is a tease, because in the myadapter, each time is to create a new view, and in view to find the corresponding control to set the corresponding value, completely useless to the cache mechanism of the ListView, resulting in a huge waste of resources.
Baseadapter's common style
Ordinary style is the upgrade version of the Myadapter, the place to upgrade is in the GetView, the tease is not used in the ListView cache mechanism, in the ordinary style this drawback will be remedied.
The following is an ordinary GetView method code:
PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {/********** Common Method ***************/ if(Convertview = =NULL){//To determine if Convertview has been cached, this decision avoids creating a large number of view, thus greatly saving resourcesConvertview = This. Minflater.inflate (R.layout.item,NULL); } ImageView image = (ImageView) Convertview.findviewbyid (r.id.iv_image); TextView title = (TextView) Convertview.findviewbyid (r.id.tv_title); TextView content = (TextView) Convertview.findviewbyid (r.id.tv_title);//Associated dataImage.setimageresource (Mlist.get (position). Itemimageresid); Title.settext (Mlist.get (position). Itemtitle); Content.settext (Mlist.get (position). itemcontent);returnConvertview;/********************************/}
The difference between the ordinary and the tease is that the common view is the Convertview of the system cache, which can avoid creating a large number of view, thus saving resources greatly.
But Findviewbyid still wastes a lot of time, which is why this method can only be referred to as the common-style reason.
The literary style of Baseadapter
The two in GetView is time-consuming:
-Create a large number of view
-Findviewbyid Find Control
We solved the first time-consuming operation through the common formula, and then we started to solve the second time-consuming operation.
This method was proposed by a developer at the Google developer conference in 2013, and the process is divided into:
1. Create the Viewholder inner class that contains all the control variables for the ListView single-line interface layout;
2. In GetView to prepare the variable viewholder, and then determine whether the Convertview is empty, the null is the 3rd step, otherwise turn 4th step;
3. Use Inflater to create Convertview, instantiate Viewholder, use Findviewbyid to instantiate the three controls in Viewholder, next, the most important, Use the Settag method to associate Convertview with Viewholder (see Code), because Convertview is cached by the system, so Viewholder is also cached;
4. Save a lot of time by using the Gettag method to remove the Viewholder and then populating the controls in the Viewholder with the data instead of using the Findviewbyid to find the controls first.
Here is the code for the Myadapter class GetView method:
PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {/************* literary Style ***************/Viewholder Viewholder =NULL;if(Convertview = =NULL) {Convertview = This. Minflater.inflate (R.layout.item,NULL); Viewholder =NewViewholder (); Viewholder.image = (ImageView) Convertview.findviewbyid (r.id.iv_image); Viewholder.title = (TextView) Convertview.findviewbyid (r.id.tv_title); Viewholder.content = (TextView) Convertview.findviewbyid (r.id.tv_content);//associating Viewholder with ConvertviewConvertview.settag (Viewholder); }Else{Viewholder = (Viewholder) convertview.gettag (); } viewHolder.image.setImageResource (Mlist.get (position). Itemimageresid); ViewHolder.title.setText (Mlist.get (position). Itemtitle); ViewHolder.content.setText (Mlist.get (position). itemcontent);returnConvertview;/*********************************/} class viewholder{ PublicImageView image; PublicTextView title; PublicTextView content; }
By this approach, a large number of Findviewbyid are avoided, thus saving time considerably.
Summarize
Tease, ordinary, literary style is gradually optimized, I can learn that we should be on the control of the internal mechanism of the relevant design patterns have a certain understanding, so as to understand the API why this design, so as to be flexible to use. In addition, sometimes you can try a different way, literary style in the use of Settag to cache Viewholder belong to this.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Android Adapter Series" Baseadapter Learning Notes