Typical wording for optimizing custom adapter using Viewholder in Android

Source: Internet
Author: User
Tags unique id

public class Markeritemadapter extends baseadapter{private Context mcontext = null;    Private list<markeritem> mmarkerdata = null;        Public Markeritemadapter (context context, list<markeritem> markeritems) {mcontext = context;    Mmarkerdata = Markeritems;    } public void Setmarkerdata (list<markeritem> markeritems) {mmarkerdata = Markeritems;        } @Override public int getcount () {int count = 0;        if (null! = Mmarkerdata) {count = Mmarkerdata.size ();    } return count;        } @Override public Markeritem getItem (int position) {Markeritem item = NULL;        if (null! = Mmarkerdata) {item = Mmarkerdata.get (position);    } return item;    } @Override public long getitemid (int position) {return position; } @Override public View getView (int position, view Convertview, ViewGroup parent) {Viewholder Viewholder = NULL;            if (null = = Convertview) {Viewholder = new Viewholder ();            Layoutinflater minflater = Layoutinflater.from (Mcontext);            Convertview = minflater.inflate (R.layout.item_marker_item, NULL);            Viewholder.name = (TextView) Convertview.findviewbyid (r.id.name);            Viewholder.description = (TextView) convertview. Findviewbyid (r.id.description);            Viewholder.createtime = (TextView) convertview. Findviewbyid (R.id.createtime);        Convertview.settag (Viewholder);        } else {Viewholder = (Viewholder) convertview.gettag ();        }//Set item values to the Viewholder:markeritem Markeritem = GetItem (position);            if (null! = Markeritem) {ViewHolder.name.setText (Markeritem.getname ());            ViewHolder.description.setText (Markeritem.getdescription ()); ViewHolder.createTime.setText (Markeritem.getcreaTedate ());    } return Convertview;        } private static class Viewholder {TextView name;        TextView description;    TextView Createtime; }}

Where Markeritem is a custom class that contains fields such as Name,description,createtime and has the appropriate get and set methods.

  Viewholder is an internal class that contains individual controls in a single project layout.

The layout of individual items, namely R.layout.item_marker_item, is as follows:

<?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"     android:padding= "5DP" >    <textview        android:id= "@+id/name"        android: Layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "Name"        android: Textsize= "20SP"        android:textstyle= "bold"/>    <textview        android:id= "@+id/description        " Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "Description"        android:textsize= "18sp"/>    <textview        android:id= "@+id/createtime"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "Createtime"        android: Textsize= "16SP"/></linearlayout>

This example is also available in the official API demos:

List14 in the package Com.example.android.apis.view:

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Com.example.android.apis.view;import Android.app.listactivity;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.textview;import Android.widget.imageview;import Android.graphics.bitmapfactory;import Android.graphics.bitmap;import Com.example.android.apis.r;/** * Demonstrates how to write a efficient list adapter. The adapter used in this example binds * to an ImageView and to a TextView for each row in the list. * To work efficiently The adapter implemented here uses a techniques: *-It reuses the Convertview passed to GetView (  ) to avoid inflating View when it's not necessary *-it uses the Viewholder pattern to avoid calling Findviewbyid () when It is not necessary * * 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 calls to Findviewbyid () Eve Ry Time GetView () is invoked.  */public class List14 extends Listactivity {private static class Efficientadapter extends Baseadapter {private        Layoutinflater Minflater;        Private Bitmap MIcon1;        Private Bitmap MIcon2; Public Efficientadapter (Context context) {//Cache the LayoutiNflate to avoid asking for a new one each time.            Minflater = Layoutinflater.from (context);            Icons bound to the rows.            MIcon1 = Bitmapfactory.decoderesource (Context.getresources (), r.drawable.icon48x48_1);        MIcon2 = Bitmapfactory.decoderesource (Context.getresources (), r.drawable.icon48x48_2);         /** * The number of the items in the list are determined by the number of speeches * in our array. * * @see Android.widget.listadapter#getcount () */public int getcount () {return D        Ata.length; }/** * Since The data comes from a array, just returning the index is * sufficent-get at the D Ata.         If we were using a more complex data * structure, we would return whatever object represents one row in the         * list.            * * @see android.widget.listadapter#getitem (int) */public Object getItem (int position) { RetuRN position;         }/** * Use the array index as a unique ID.            * * @see android.widget.listadapter#getitemid (int) */public long getitemid (int position) {        return position;         }/** * Make a view to hold each row.         * * @see android.widget.listadapter#getview (int, Android.view.View, * android.view.ViewGroup) */Public View getView (int position, View Convertview, ViewGroup parent) {//A Viewholder keeps Refere            NCEs to children views to avoid unneccessary calls//to Findviewbyid () on each row.            Viewholder Holder; When convertview are not NULL, we can reuse it directly, there are no need//to reinflate it.            We only inflate a new View when the Convertview supplied//by ListView is null. if (Convertview = = null) {Convertview = minflater.inflate (R.layout.list_item_icon_text, NULL);               Creates a viewholder and store references to the other children views//We want to bind Da                Ta to.                Holder = new Viewholder ();                Holder.text = (TextView) Convertview.findviewbyid (R.id.text);                Holder.icon = (ImageView) Convertview.findviewbyid (R.id.icon);            Convertview.settag (holder);                 } else {//Get the Viewholder back-to-get fast access to the TextView//and the ImageView.            Holder = (viewholder) convertview.gettag ();            }//Bind the data efficiently with the holder.            Holder.text.setText (Data[position]);            Holder.icon.setImageBitmap ((position & 1) = = 1? micon1:micon2);        return convertview;            } static class Viewholder {TextView text;        ImageView icon; }} @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (SavedinstaNcestate);    Setlistadapter (New Efficientadapter (this)); } private static Final string[] DATA = cheeses.scheesestrings;}

Which layout:

<?xml version= "1.0" encoding= "Utf-8"?><!--Copyright (C) The Android Open Source Project Licensed under     The Apache License, Version 2.0 (the "License");     You are not a use of this file except in compliance with the License. Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by app Licable law or agreed to in writing, software distributed under the License are distributed on a "as is" BASIS, WI     Thout warranties or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><linearlayo UT xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "Horizontal" android:layout_ Width= "Match_parent" android:layout_height= "match_parent" > <imageview android:id= "@+id/icon" Android:la Yout_width= "48dip" android:layout_height= "48dip"/> <textview Android:id= "@+id/text" android:layout_gravity= "center_vertical" android:layout_width= "0dip" Android: Layout_weight= "1.0" android:layout_height= "Wrap_content"/></linearlayout>

More articles on adapter optimization:

Http://www.cnblogs.com/over140/archive/2011/03/23/1991100.html

Http://www.cnblogs.com/halzhang/archive/2010/12/05/1896791.html

Reprint: http://www.cnblogs.com/mengdd/p/3254323.html

Typical wording for optimizing custom adapter using Viewholder in Android

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.