Android's Listview/gridview optimization

Source: Internet
Author: User

First, the least efficient GetView realization

We know that both the ListView and the GridView display are implemented through the adapter GetView.

When the amount of listview/gridview data is small, we typically do this in the least efficient way.

 1  public  View getView (int   position, View Convertview, ViewGroup parent) { 2  View item = minflater.inflate (R.layout.list_item_icon_text, null  Span style= "color: #000000;" >); 3   ((TextView) Item.findviewbyid (R.id.text)). SetText (Data[position]);  4   ((ImageView) Item.findviewbyid (R.id.icon)). Setimagebitmap ( 5  (position & 1) = = 1?  Micon1:micon2);  6  return   7 } 

When the amount of data is very large, so every time GetView will go to inflate layout, inefficient, this will let our program lag, sliding more and will be oom.

Second, the use of Android has provided a view cache mechanism to achieve Viewholder mode-to achieve view sharing

We note that the second parameter of GetView is Convertview, which is the key to the view caching mechanism. Simply say it at two points:

1. Assuming that the current page we have 7 item, then the first seven times GetView, this convertview is null

2. Let's say we go up the page, now Item8 into the pages, item1 out the page, at this time Item8 corresponding GetView Convertview is item1

With the feature of this view caching mechanism, we only need to update the Convertview data in Item8 GetView from Item1 to ITEM8. That is to say, ITEM8 and Item1 realize the sharing of view. (Well, ITEM8 and Item1 never appear together in one interface, so you really should share some resources)

And this is the so-called viewholder pattern.

@Override PublicView GetView (intposition, View Convertview, ViewGroup arg2) {List log.i ("Xerrard", "GetView" + position + "" +Convertview); Viewholder Viewholder=NULL; if(Convertview = =NULL) {Viewholder=NewViewholder (); Convertview= Inflater.inflate (R.layout.item,NULL); Viewholder.image=(ImageView) Convertview.findviewbyid (r.id.img); Viewholder.text=(TextView) Convertview.findviewbyid (r.id.txt);            Convertview.settag (Viewholder); }Else{Viewholder=(Viewholder) Convertview.gettag ();            } viewHolder.image.setImageBitmap (Imgs.get (position));            ViewHolder.text.setText (Texts.get (position)); returnConvertview; }        classviewholder{ImageView image;        TextView text; }

Third, asynchronous loading of Listview/gridview.

Many times we will need to download some pictures online to display, if the main thread to do the download, it is likely to cause the ANR, so need to implement the child thread. (even images in local storage are recommended to be implemented with child threads, and local IO operations can sometimes cause ANR)

We use the Asynctask in Android to implement the download operation

1 /**2 * Created by Xuqiang on 15-12-16.3  */4  Public classImagetaskextendsAsynctask<string, Void, bitmap> {5     PrivateImageView IV;6 String Imgurl;7      PublicImagetask (ImageView iv) {8          This. IV =IV;9     }Ten  One @Override A     protectedBitmap doinbackground (String ... param) { -Imgurl = param[0]; -         Try { theURL url =NewURL (imgurl); -             Try { -HttpURLConnection conn =(HttpURLConnection) url.openconnection (); -InputStream in =Conn.getinputstream (); +Bitmap Bitmap =Bitmapfactory.decodestream (in); -                 if(bitmap!=NULL){ +                     returnbitmap; A                 } at}Catch(IOException e) { -                 //TODO auto-generated Catch block - e.printstacktrace (); -             } -}Catch(malformedurlexception e) { -             //TODO auto-generated Catch block in e.printstacktrace (); -         } to         return NULL; +     } -  the @Override *     protected voidOnPostExecute (Bitmap result) { $         Super. OnPostExecute (result);Panax Notoginseng         if(Result! =NULL) { -             //prevent image dislocation by tag the             if(Iv.gettag ()! =NULL&&Iv.gettag (). Equals (Imgurl)) { + Iv.setimagebitmap (result); A             } the         } +     } -  $ @Override $     protected voidOnPreExecute () { -         Super. OnPreExecute (); -     } the}

And then in the GetView, we just need to viewholder the operation, pass parameters to Imagetask to deal with

            New Imagetask (viewholder.image,position);            Imagetask.execute (Imgurls.get (position));

Solving the dislocation problem in asynchronous loading of Listview/gridview

Just now we know that using the Android view caching mechanism, we can use Viewholder to optimize the efficiency of listview/gridview. But in the process of loading the picture asynchronously, it is precisely because of this view sharing mechanism, will cause the picture dislocation situation.

This question, how do we solve it.

The simplest solution is to say it online and set a tag for ImageView.

When Item1 than Item8 picture download faster, you roll down to make Item8 visible, then ImageView's tag was set to

Item8 URL, when Item1 download finished, because ITEM1 is not visible now the tag is ITEM8 URL, so does not meet the conditions,

Although downloaded but not set to ImageView, tag is always identified as the URL of the picture in the visible view.

We'll finally write down this final improvement plan.

1. Set a tag on the main thread,

1 @Override2          PublicView GetView (intposition, View Convertview, ViewGroup arg2) {3LOG.I ("Xerrard", "GetView" + position + "" +Convertview);4Viewholder Viewholder =NULL;5             if(Convertview = =NULL){6Viewholder =NewViewholder ();7Convertview = Inflater.inflate (R.layout.item,NULL);8Viewholder.image =(ImageView) Convertview.findviewbyid (r.id.img);9 Ten Convertview.settag (viewholder); One}Else{ AViewholder =(Viewholder) Convertview.gettag (); -             } - ViewHolder.image.setTag (imgurls.get (position)); theImagetask Imagetask =NewImagetask (viewholder.image); - Imagetask.execute (imgurls.get (position)); -             returnConvertview; -         } +         classviewholder{ - ImageView image; +         } A}

2. In the asynchronous Imagetask settings picture Place, judge the tag, confirm tag no problem, then set the picture

1 @Override2     protected voidOnPostExecute (Bitmap result) {3         Super. OnPostExecute (result);4         if(Result! =NULL) {5             //prevent image dislocation by tag6              If (iv.gettag () = null && iv.gettag (). Equals (Imgurl)) { 7 Iv.setimagebitmap (result);8             }9         }Ten}

Android's Listview/gridview optimization

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.