Top two we introduced the general optimization of the ListView method as well as the Disklrucache optimization listview, see Android-----Take you step by step to optimize the ListView (i) and Android-----Take youstep-by-step optimization of the ListView (ii), this article we will be from the memory cache angle to complete the ListView optimization, using LRUCache, its main algorithm principle is to use the most recently used objects with strong references to store the Linkedhashmap, and the least recently used object is removed from memory before the cache value reaches the preset value, and no fixed cache size is compliant with all applications, we should set a reasonable cache size based on the state of our application. Below we use the example to learn how LRUCache is used specifically:
First define the layout file that displays the ListView: Listview.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:o rientation= "vertical" > <listview android:id= "@+id/listview" android:layout_width= "Match_ Parent " android:layout_height=" match_parent "> </ListView></LinearLayout>
then define the style of each item display 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=" match_parent " android:o rientation= "vertical" > <imageview android:id= "@+id/imageview" android:layout_width= "50DP" android:layout_height= "50DP" /> <textview android:id= "@+id/textview" android: Layout_width= "100DP" android:layout_height= "50DP" android:layout_torightof= "@id/imageview" android:layout_margintop= "20DP" android:layout_marginright= "70DP" /></relativelayout>
Next is the most important listviewadapter adapter content, the code is a bit of length, first paste it out, then slowly explain:
public class Listviewadapter extends baseadapter{//stores all paths that will be accessed public list<string> list;public lrucache< String, bitmap> lrucache;public layoutinflater inflater;public ListView listview;public int reqwidth;public int Reqheight;public set<imageasynctask> tasks = new hashset<listviewadapter.imageasynctask> ();p ublic Listviewadapter (Context context,list<string> list,lrucache<string, bitmap> Lrucache,listview ListView, ImageView ImageView) {this.list = List;this.lrucache = Lrucache;this.inflater = Layoutinflater.from (context); This.listview = ListView; Layoutparams params = Imageview.getlayoutparams (); reqwidth = Params.width;reqheight = Params.height;} @Overridepublic int GetCount () {return list.size ();} @Overridepublic String getItem (int position) {return list.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {view view = null; Viewholder holder = null;if (CONvertview = = null) {view = Inflater.inflate (R.layout.item, null); holder = new Viewholder (); Holder.imageview = (ImageView) View.findviewbyid (r.id.imageview); Holder.textview = (TextView) View.findviewbyid (R.id.textview); View.setTag ( Holder);} Else{view = Convertview;holder = (viewholder) View.gettag ();} Set tag for ImageView and TextView to prevent disorderly ordering holder.imageView.setTag (position); Holder.textView.setTag (position+ "#"); return View;} /** * Add the current key value corresponding to the bitmap to LRUCache * @param key * @param bitmap */public void Addbitmaptomemorycache (String key,bitmap bitm AP) {if (Getbitmapfrommemorycache (key) = = null) {Lrucache.put (key, bitmap);}} /** * Gets the Bitmap object corresponding to key from LRUCache * @param key * @return */public Bitmap getbitmapfrommemorycache (String key) {return Lruca Che.get (key);} /** * Load a picture on a location * @param URL * @param position */public void LoadImage (int position) {//Get to position location corresponding urlstring URL = ge TItem (position); Bitmap Bitmap = Null;bitmap = Getbitmapfrommemorycache (URL); if (Bitmap! = null) {//indicates that there is a corresponding Bitmap in the cache for this URL, the BITM is obtained directlyThe AP and shows to the listView above imageView ImageView = (imageView) listview.findviewwithtag (position); TextView TextView = (TextView) Listview.findviewwithtag (position+ "#"); if (ImageView! = null) Imageview.setimagebitmap ( bitmap); if (TextView! = null) Textview.settext ("fetched from Cache");} else{//The open thread loads the picture from the network imageasynctask task = new Imageasynctask (listView, position); Task.setonimageloadlistener (new Onimageloadlistener () {@Overridepublic void Onsuccessload (Bitmap Bitmap) {System.out.println ("load picture succeeded");} @Overridepublic void Onfailureload () {System.out.println ("Load picture failed");}}); Tasks.add (Task); Task.execute (URL);//Open line loads load picture}}/** * Pause All tasks (in order to prevent the thread is still in the requested state while sliding) */public void Canceltask () {if ( tasks = null) {for (Imageasynctask task:tasks) Task.cancel (FALSE);//Pause Task}}/** * Compress picture * @param in * @param reqwidth * @ Param reqheight * @return */public static Bitmap decodesamplebitmapfromstream (InputStream in,int reqwidth,int reqheight) {//Set Bitmapfactory.options Injustdecodebounds property to True to prohibit allocating memory for bitmap bitmapfactory.options Options = nEW bitmapfactory.options (); options.injustdecodebounds = true;byte[] data = Inputstreamtobytearray (in);// The purpose of this call is to obtain the width and height of the original image, but this operation is not a write memory operation bitmap Beforebitmap = bitmapfactory.decodebytearray (data, 0, data.length, options ); options.insamplesize = calculateinsamplesize (options, Reqwidth, reqheight);// Set this load image to be loaded into memory Options.injustdecodebounds = false; Bitmap Afterbitmap = bitmapfactory.decodebytearray (data, 0, data.length, options); return afterbitmap;} /** * Calculate the compression ratio * @param options * @param reqwith * @param reqheight * @return */public static int calculateinsamplesize (BITM Apfactory.options options,int reqwidth,int reqheight) {//the wide, high int width = options.outwidth;int height of the real picture via the parameter Options = Options.outheight;int Insamplesize = 1;//The initial value is not compressed if (Width > reqwidth | | height > reqheight) {//calculates the original width and the existing width, The ratio of the original height to the existing high is int widthRatio = Math.Round ((float) width/(float) reqwidth); int heightratio = Math.Round ((float) height/( float) reqheight);//Select the smaller of the two ratios so that the picture is displayed completely insamplesize = WidthRatio < HeighTratio? Widthratio:heightratio;} return insamplesize;} /** * Convert InputStream to byte array * @param in * @return */public static byte[] Inputstreamtobytearray (InputStream in) {Bytearrayo Utputstream outputstream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len;try {while (len = In.read (bu Ffer))! =-1) {outputstream.write (buffer, 0, Len);}} catch (IOException e) {e.printstacktrace ();} Finally{try {in.close (); Outputstream.close ();} catch (IOException e) {e.printstacktrace ();}} return Outputstream.tobytearray ();} Static class Viewholder{imageview ImageView; TextView TextView;} Class Imageasynctask extends Asynctask<string, Void, bitmap>{public ListView listview;public Onimageloadlistener listener;public int position;public imageasynctask (listview listview,int position) {This.listview = ListView; This.position = position;} public void Setonimageloadlistener (Onimageloadlistener listener) {This.listener = listener;} @Overrideprotected Bitmap doinbackground (String ... params) {string urlstring = Params[0]; URL url = null;inputstream in = null; HttpURLConnection connection = null; Bitmap Bitmap = null;try {url = new URL (urlstring); connection = (HttpURLConnection) url.openconnection (); in = CONNECTION.G Etinputstream (); bitmap = Decodesamplebitmapfromstream (in, Reqwidth, reqheight);//Add current bitmap to cache if (bitmap! = null) Lrucache.put (urlstring, bitmap);} catch (Exception e) {e.printstacktrace ();} return bitmap;} @Overrideprotected void OnPostExecute (Bitmap result) {if (result! = null) {listener.onsuccessload (result); ImageView ImageView = (ImageView) listview.findviewwithtag (position); TextView TextView = (TextView) Listview.findviewwithtag (position+ "#"); if (ImageView! = null) Imageview.setimagebitmap ( result); if (TextView! = null) Textview.settext ("obtained from the Network");} Elselistener.onfailureload ();}}}
39 lines of GetView method code is our usual use of the listview of the general wording, multiplexing Convertview and for each view set Viewholder, in order to prevent the picture loading chaos, 55th, 56 Lines We set the tag mark for ImageView and TextView respectively;
The Addbitmaptomemorycache of line 65th is used to add the current bitmap bitmap to the LRUCache because LRUCache itself is actually implemented by Linkedhashmap, and all calls are put methods;
The Getbitmapfrommemorycache method in line 78th is used to read the bitmap bitmap of the specified key value from the LRUCache cache;
The 88th line of LoadImage is our core code, first 91st line to get the URL of the image to be loaded by the current item entry by calling the GetItem method, followed by 93 rows of calls Getbitmapfrommemorycache to see if there is a bitmap of the specified key value in the cache, the 94th line is judged, and if bitmap is present, it enters the IF statement block, 97, 98 rows through Findviewwithtag to obtain the ImageView and TextView of the corresponding entry, and displays the cached picture currently fetched to the current item, or into the Else statement block of 103 rows if it does not exist in the current cache. The 106 row defines a imageasynctask picture load thread, and in 119 rows The current thread is added to the Tasks collection of the set<imageasynctask> type so that we can then control the loading of the picture thread. Line 120th invokes the Execute method, passing in the URL that currently needs to load the picture;
Execute will call Imageasynctask's doinbackground method to load the picture, here's the picture loading method and the previous Android-----take you step by step to optimize the ListView (ii) Is consistent, unclear friends can look at the previous blog, in addition to this also used in the image compression technology, do not know how to see the Android-----solve bitmap memory Overflow of a method (image compression technology), After the picture compression is finished, the No. 245 line will be added to the LRUCache, and then the UI can be updated in the onpostexecute bitmap.
The last is the Mainactivity method:
public class Mainactivity extends Activity implements Onscrolllistener {public lrucache<string, bitmap> memorycache;public int start_index;public int end_index;public listviewadapter adapter;public Boolean isInit = true; Public string[] Images = {"Http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "HTTP://IMG.MY.CSDN.N Et/uploads/201407/26/1406383291_6518.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg ", "Http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg", "http://img.my.csdn.net/uploads/201407/26/1406 383290_1042.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg "," http://img.my.csdn.ne T/uploads/201407/26/1406383265_8550.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg ", "Http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg", "http://img.my.csdn.net/uploads/201407/26/14063 83264_8243.jpg "," http://img.my.cSdn.net/uploads/201407/26/1406383248_3693.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg ", "Http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg", "HTTP://IMG.MY.CSDN.NET/UPLOADS/201407/2 6/1406383242_9576.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg "," http://img.my.c Sdn.net/uploads/201407/26/1406383219_5806.jpg "," http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg ", "Http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg", "HTTP://IMG.MY.CSDN.NET/UPLOADS/201407/2 6/1406383213_3557.jpg "," Http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg "};p ublic list<string > list = new arraylist<string> ();p ublic ListView listview;public ImageView ImageView; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.listview); MemoryCache = Getlrucache (); for (int i = 0;i < 50;i++) {int index = i% (images.length); List.add (Images[index]);} ListView = (ListView) Findviewbyid (R.id.listview); Layoutinflater Inflater = Layoutinflater.from (this); View view = Inflater.inflate (R.layout.item, null); ImageView = (ImageView) View.findviewbyid (r.id.imageview); adapter = New Listviewadapter (this, list, MemoryCache, ListView, ImageView); Listview.setonscrolllistener (this); Listview.setadapter (adapter);} /** * Get LruCache Object * @return */public lrucache<string, bitmap> Getlrucache () {lrucache<string, bitmap> cache = Null;//gets the available memory size int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);//Set its 1/8 to our memory cache size int cacheSize = Maxmemory/8;cache = new lrucache<string, bitmap> (cacheSize) {@Overrideprotected int sizeOf (String key, Bitmap Value) {//Returns the size of the current picture (GetByteCount is used to return the number of bytes of memory occupied by the current bitmap) return Value.getbytecount ()/1024;}}; return cache;} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {Start_ index = firstvisibleItem;end_index = Start_index + visibleitemcount;if (isinit = = True && visibleitemcount > 0) {for (int i = start_in Dex;i < end_index;i++) {adapter.loadimage (i); }isinit = false;}} @Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {if (scrollstate = = AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {//= stop sliding, this time can load picture for (int i = Start_index;i < end_index;i++) { Adapter.loadimage (i); }}else{adapter.canceltask ();}}}
Here the key code is the 55th line of the Getlrucache method, first through the runtime.getruntime (). MaxMemory () to obtain the currently available memory size, followed by the CacheSize is the size of the memory we set for LRUCache, and the sizeof method on line 66th is used to return the size of the current picture;
Similarly, similar to the use of Disklrucache in the previous article, here we also set the ListView sliding event, to ensure that it does not load the picture during the sliding process of the request operation, slide stop and then to load the picture;
Another hint, don't forget to add access to the network:
<uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>
Click to download SOURCE!!!!!
I have integrated the previous blog and this code into a full ListView version with Disklrucache and LRUCache caches:
Click to download INTEGRATED SOURCE!!!!!
Android-----Take you step by step to optimize the ListView (iii)