Android ListView Understanding of Baseadapter

Source: Internet
Author: User

The ListView is one of the more common components of the Android development process, and it presents the data as a list. Generally, a ListView consists of the following three elements:

1.View, used for a presentation list, usually specified by an XML. Everyone knows that the Android interface is basically done by an XML file, so the ListView interface takes the XML definition for granted. For example, "Android" is often used in a ListView. R.layout.simple_list_item_1 "is a well-defined XML file within the Android system.

2. Adapter, used to map different data to the view. Different data correspond to different adapters, such as Arrayadapter,cursoradapter, Simpleadapter, etc., they are able to map arrays, pointers to data, maps and other data to the view. It is also because of the existence of the adapter, so that the use of the ListView is quite flexible, after the processing of the adapter, in view all the data mapping is the same. 3. Data, specific mapping of the data and resources, can be strings, pictures, etc., through the adapter, the data will be realistic to the ListView. All the data and resources to be displayed on the ListView are done via adapters.

Existing adapters of the system can display basic data on a ListView, such as an array, the data that the cursor points to, and the data in the map. But in actual development these systems have implemented adapters that sometimes do not meet our needs. And the system comes with multi-select features the ListView will have some problems in the actual use process. To implement a complex listview can be accomplished by inheriting the ListView and overriding the appropriate method, as well as by inheriting the Baseadapter. As you can see from the documentation, Arrayadapter,cursoradapter, Simpleadapter are inherited from Baseadapter. So by inheriting Baseadapter can complete their own adapter, can be any complex combination of data and resources to any of the results you want to show to everyone.

After inheriting baseadapter, you need to rewrite the following four methods: Getcount,getitem,getitemid,getview.

The ListView drawing process is as follows: first, the system will call the GetCount method to get the number of items before drawing the ListView. Once each item is drawn, a GetView method is called, within which you can reference the predefined XML to determine the effect of the display and return a View object to be displayed as an item. It is also in this process to complete the main adapter conversion function, the data and resources to the developers want to show the effect. It is also the repeated invocation of GetView, making the use of the ListView simpler and more flexible. These two methods are the most important in customizing the ListView display, and as long as the two methods are rewritten, the ListView can be displayed exactly as the developer asks. The GetItem and Getitemid methods are called when the ListView response method is called. So to ensure that the various methods of the ListView are valid, these two methods also have to be rewritten. For example, if the function of the Getitemid method is not fulfilled, the desired result will not be obtained when invoking the Getitemidatposition method of the ListView, because the method is the Getitemid method that invokes the corresponding adapter.

After all, the development of the use of a variety of adapter feel the most comfortable or baseadapter, although it is a bit more troublesome than other adapters, but use it to achieve a lot of their favorite list layout, such as ListView, GridView, Gallery, Spinner and so on. It is directly inherited from the interface class adapter, the use of baseadapter need to rewrite a lot of methods, the most important of which is getview, because this will involve the ListView optimization and other issues, other methods can refer to the linked article

Baseadapter is somewhat different from other adapter, other adapter can set data directly in its construction method, such as

Simpleadapter adapter = new Simpleadapter (this, GetData (), R.layout.list_item, New string[]{"img", "title", "Info", new Int[]{r.id.img, R.id.title, R.id.info}});

But in Baseadapter you need to implement a class that inherits from Baseadapter, and overrides many of the methods inside, such as

 class Myadapter extends Baseadapter {private context context;        Public Myadapter (Context context) {This.context = context; } @Override public int getcount () {//How many items is in the data set represented by this Ada Pter.        (Number of entries in the data set represented in this adapter) return 0; } @Override public Object getItem (int position) {//Get the data item associated with the SPECIF IED position in the data set.        (Gets the data item corresponding to the specified index in the dataset) return null;  } @Override Public Long Getitemid (int. position) {//Get the row ID associated with the specified Position in the list.        (The row ID that corresponds to the specified index in the list) return 0;  } @Override public view getView (int position, view Convertview, ViewGroup parent) {//Get a view            That displays the data at the specified position in the data set.        return null; }            }

There is no difficulty in this, but this getview method must be handled well and is the most troublesome.

The first: There is no processing, it is not recommended to write. If the amount of data is low, but if the list item data is very large, the view will be recreated each time, set the resources, severely affect performance, so from the beginning do not use this way

        @Override public        View getView (int position, view Convertview, ViewGroup parent) {            view item = minflater.inflate (R . Layout.list_item, null);            ImageView img = (ImageView) Item.findviewbyid (r.id.img)             TextView title = (TextView) Item.findviewbyid (r.id.title);            TextView info = (TextView) Item.findviewbyid (r.id.info);            Img.setimageresource (r.drawable.ic_launcher);            Title.settext ("Hello");            Info.settext ("World");                        return item;        }

The second ListView optimization: By Caching Convertview, this method of caching Contentview can be used to determine if the view is not created in the cache, and if it already exists, it can take advantage of the view in the cache, which improves performance

        Public View GetView (int position, View Convertview, ViewGroup parent) {            if (Convertview = = null)            {                Convertview = minflater.inflate (R.layout.list_item, null);            }                        ImageView img = (ImageView) Convertview.findviewbyid (r.id.img)             TextView title = (TextView) Convertview.findviewbyid (r.id.title);            TextView info = (TextView) Convertview.findviewbyid (r.id.info);            Img.setimageresource (r.drawable.ic_launcher);            Title.settext ("Hello");            Info.settext ("World");                        return convertview;        }

The third ListView optimization: Implemented by Convertview+viewholder, Viewholder is a static class, and the key benefit of using Viewholder is to cache the view that displays the data, which speeds up the responsiveness of the UI.

When we judge Convertview = = NULL, if it is empty, it will be assigned to Convertview according to the item layout (XML) of the list that was designed. and generate a viewholder to bind the individual view controls inside the Converview (those controls inside the XML layout). Then use the Convertview Settag to set the Viewholder to tag so that the system draws the ListView from the tag the second time it is drawn. (See the code below)

If Convertview is not empty, it will use Convertview's Gettag () to obtain a viewholder.

    Define outside first, Viewholder static class Viewholder {public ImageView img;        Public TextView title;    public TextView info;            }//then rewrites the GetView @Override public View getView (int position, view Convertview, ViewGroup parent) {            Viewholder Holder;                if (Convertview = = null) {holder = new Viewholder ();                Convertview = minflater.inflate (R.layout.list_item, NULL); Holder.img = (ImageView) Item.findviewbyid (r.id.img) Holder.title = (TextView) Item.findviewbyid (r.id.title)                ;                Holder.info = (TextView) Item.findviewbyid (r.id.info);            Convertview.settag (holder);                }else {holder = (Viewholder) convertview.gettag ();                Holder.img.setImageResource (R.drawable.ic_launcher);                Holder.title.setText ("Hello");            Holder.info.setText ("World"); } return ConvErtview; }

Here, someone might ask Viewholder static class binding cache Convertview and direct use of Convertview what is the difference, whether duplicate

Here, the authorities gave an explanation.

Two ways to lift adapter

To work efficiently the adapter implemented here uses the techniques:
-it reuses the Convertview passed to GetView () to avoid inflating View when It's not necessary

(Translate: Reuse cache Convertview pass to GetView () method to avoid populating unnecessary views)
-it uses the Viewholder pattern to avoid calling Findviewbyid () when It's not necessary

(Translate: Use Viewholder mode to avoid unnecessary calls to Findviewbyid (): Because too many Findviewbyid also affect performance)
The role of the Viewholder class
-the Viewholder pattern consists in storing a data structure in the tag of the view
Returned by GetView (). This data structures contains references to the views we want to bind data to,
Thus avoiding calling to Findviewbyid () every time GetView () is invoked

Viewholder mode stores a data structure in the label (tag) of the view returned by the GetView () method, which contains a pointer to our

A reference to the view to bind the data to avoid calling Findviewbyid () at each call to GetView ())

Example one: Customizing the ListView layout with Baseadapter
Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >    <listview        android:id= "@+id/lv"        android:layout_width= "Fill_parent"        android:layout_height= "wrap_content"        android:fastscrollenabled= "true"        /></linearlayout>

List_item.xml

 <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:layout_width=" match_parent "android:layout_height=" match_parent "android:orientation=" Horizo Ntal "> <imageview android:id=" @+id/img "android:layout_width=" Wrap_content "Android:layout_ height= "Wrap_content"/> <linearlayout android:layout_width= "Fill_parent" android:layout_he            ight= "wrap_content" android:orientation= "vertical" > <textview android:id= "@+id/tv" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:textsize             = "20sp"/> <textview android:id= "@+id/info" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:textsize= "14sp"/> </linearlayout&    Gt </linearlayout> 

Activity

Package Com.loulijun.demo17;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;import Java.util.map;import Android.app.activity;import Android.content.context;import Android.os.Bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.listview;import    Android.widget.textview;public class Demo17activity extends Activity {private ListView LV;    Private list<map<string, object>> data;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        LV = (ListView) Findviewbyid (r.id.lv);        Gets the data that will be bound to GetData ().        Myadapter adapter = new Myadapter (this);    Lv.setadapter (adapter); } private List<map<string, object>> GetData () {list<map<string, object>> List = NEW arraylist<map<string, object>> ();        Map<string, object> map;            for (int i=0;i<10;i++) {map = new hashmap<string, object> ();            Map.put ("img", R.drawable.ic_launcher);            Map.put ("title", "Taekwondo");            Map.put ("info", "Happiness from Life ...");        List.add (map);    } return list;        }//viewholder Static class Viewholder {public ImageView img;        Public TextView title;    public TextView info;        } public class Myadapter extends Baseadapter {private Layoutinflater minflater = null; Private Myadapter (Context context) {//the layout is loaded according to context contexts, here is the demo17activity itself, which is this THIS.MINFL        Ater = Layoutinflater.from (context); } @Override public int getcount () {//how Many items is in the data set represented by this ADAP            ter.        The number of entries in the data set represented in this adapter return data.size ();    }    @Override Public Object GetItem (int. position) {//Get the data item associated with the specified p            Osition in the data set.        Gets the data item corresponding to the specified index in the data set return position; } @Override Public Long Getitemid (int. position) {//get The row ID associated with the specified            Position in the list.        Gets the row ID in the list that corresponds to the specified index, return position;        //get a View that displays the data on the specified position in the data set.            Gets a view of the specified index in the dataset to display the data @Override public view GetView (int position, view Convertview, ViewGroup parent) {            Viewholder holder = null;                If the cache Convertview is empty, you need to create a view if (Convertview = = null) {holder = new Viewholder ();                Load layout According to custom item layout Convertview = Minflater.inflate (R.layout.list_item, NULL);    Holder.img = (ImageView) Convertview.findviewbyid (r.id.img);            Holder.title = (TextView) Convertview.findviewbyid (r.id.tv);                Holder.info = (TextView) Convertview.findviewbyid (r.id.info);            Save the set layout to the cache and set it in the tag so that the tag convertview.settag (holder) can be removed conveniently.            }else {holder = (Viewholder) convertview.gettag ();            } holder.img.setBackgroundResource ((Integer) data.get (position). Get ("img"));            Holder.title.setText (String) data.get (position). Get ("title"));                        Holder.info.setText (String) data.get (position). Get ("info"));        return convertview; }            }}

The results of the operation are as follows:


Example two: Application of gallery on Baseadapter

Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >        <imageview         android:id= "@+id/img"        android:layout_width= "480px"        android:layout_height= "480px"        android:layout_gravity= "center"        />    <gallery         android:id= "@ +id/gallery "        android:layout_width=" fill_parent "        android:layout_height=" Wrap_content "        android: spacing= "3DP"        android:layout_gravity= "Bottom"        /></linearlayout>

Activity: This part of the GetView is not optimized, debugging for a long time has not been transferred, temporarily or the most basic method. Will specifically find a time to write the gallery memory leaks, because the picture of a lot of resources will cause out of memory errors

Package Com.loulijun.demo16;import Android.app.activity;import Android.content.context;import android.os.Bundle; Import Android.view.view;import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.baseadapter;import Android.widget.gallery;import Android.widget.imageview;public Class    Demo16activity extends Activity {private Gallery mgallery;    Private ImageView mimg;            Image array Private int[] pics = {R.drawable.pic1, r.drawable.pic2, R.DRAWABLE.PIC3,    R.drawable.pic4, R.DRAWABLE.PIC5, r.drawable.pic6};        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Mimg = (ImageView) Findviewbyid (r.id.img);        MGallery = (Gallery) Findviewbyid (r.id.gallery);        Myadapter adapter = new Myadapter (this);        Mgallery.setadapter (adapter); Mgallery.setonitemclicklistener (New Gallery.onitEmclicklistener () {@Override public void Onitemclick (adapterview<?> adapter, view view            , int position, long Arg3) {Mimg.setimageresource (pics[position]);    }                    });        }//Internal class Myadapter extends Baseadapter {//used to receive a context context object passed over the private context;        Constructor public Myadapter (context context) {This.context = context;        } @Override public int getcount () {//returns the picture array size return pics.length;        } @Override public Object getItem (int position) {//returns the index position according to the selection return position;        } @Override public long getitemid (int position) {//returns the index position according to the selected item ID return position; }//Not optimized GetView, this part can use recycle () to free up memory, or bitmapfacotry.options shrink, or soft reference, or control the size of the picture resources and so many ways, find time to write @Overrid E public View getView (int pOsition, View Convertview, ViewGroup parent) {ImageView img = new ImageView (context);            Img.setadjustviewbounds (TRUE);            Img.setimageresource (Pics[position]);            Img.setscaletype (ImageView.ScaleType.FIT_XY);                        Img.setlayoutparams (New Gallery.layoutparams (120,120));        return img; }        }}

Running effect: The principle is the same, but the layout of the load when there will be a difference, but this small difference also makes people angry enough

Android ListView Understanding of Baseadapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.