Android's Strongest ListView Optimization solution in History
Source: Internet
Author: User
<span id="Label3"></p><span style="font-size:18px"><span style="font-size:18px">in Android development, the ListView is a very important component, it is in the form of a list of data based on the long-adaptive display of specific content, users can freely define the layout of each column of the listview, <span style="white-space:pre"></span> But when the ListView has a lot of data to load, it takes up a lot of memory and affects Performance.<br></span></span><span style="font-size:18px"><span style="font-size:18px"><br></span></span><span style="font-size:18px"><span style="font-size:18px">the focus of this article is to describe how to optimize the ListView in the following ways. </span></span><span style="font-size:18px"><span style="font-size:18px"><br></span></span><span style="color:rgb(255,0,0)"><span style="color:rgb(255,0,0)">1, Convertview Reuse</span></span><br>This is said in the Android sdk:<p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><span style="white-space:pre"></span>The old view to reuse, if Possible. Note:you should check the This view is non-null and of a appropriate type before using. If It isn't possible to convert this view to display the correct data, This method can create a new view</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">Use good convertview to reuse View, avoid every getView () new. The core principle of the ListView is to reuse the view, if the reuse view does not change the width, reuse view can reduce the memory allocation/recycling caused by the redistribution of the cache;</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"></p></p><pre name="code" class="html"><pre name="code" class="html"><?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/listview" android:layout_width= "fill_ Parent " android:layout_height=" fill_parent " android:cachecolorhint=" #00000000 "></ListView> </LinearLayout></pre></pre>The Android:layout_height property value of the ListView is set to "fill_parent" or "wrap_content", but the convertview mechanism is the same<p><p></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">If set to fill_parent: the Convertview of item displayed on the screen is empty, the convetview of the newly generated item is not empty<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">If set to Wrap_content: only the Convertview of the first item is null, the other is not empty</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">Summarize:</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">At the initial display, each time an item is displayed, the GetView method is called once but the Covertview is empty each time it is called (because there is no old view), when the display is Finished. If the screen moves and causes some item (or View) to run outside the screen, if there is a new item that needs to be generated, then the Convertview parameter in the GetView method that is called when the item is displayed is not Null. Instead of the view (old View) that moved out of the screen, all we have to do is populate the recycled view with the item that needs to be displayed, and finally note that Convertview is not just the initial display of the item, There are those item that have already started to move into the screen but have not yet been recovered by the VIEW.<br><br></p></p><span style="color:#ff0000"><span style="color:#ff0000">2, viewholder Optimization</span></span><br><span style="text-align:justify"><span style="text-align:justify">the reason for using Viewholder is that the Findviewbyid method is time consuming, and if the number of controls is too large, it can seriously affect performance, and the use of Viewholder is primarily to save this Time. Direct access to view via Settag,gettag</span></span><br><span style="text-align:justify"><span style="text-align:justify">summary:</span></span><span style="text-align:justify"><span style="text-align:justify"></span></span><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">The Settag and Gettag methods of view are very simple, when actually writing code, a view is not just to display some strings, pictures, and sometimes we need them to carry some other data so that we can recognize the view or other Operations. So the Android designers created the Settag (Object) method to hold some data and view bindings, and we can understand that this is the label of the view as well as the view as a container to hold some Data. We can also use the Gettag () method to extract the Data.</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">Here Settag and Gettag people should have understood. Returning to the above topic, we bind the data we want to display on Convertview by Convertview's Settag method and Gettag Method. If Convertview is the first to show we create a new holder object with which to bind, and return it at the end through return convertview, to display, if Convertview is recycled then we don't have to create a new holder object, Just need to get the original bound holder out and add the new Data.</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"></p></p><pre name="code" class="java"><pre name="code" class="java">Class viewholder{ ImageView img; TextView name;} Public View getView (int position, View convertview, viewgroup parent) { viewholder holder = null; If (convertview==null) { convertview = inflater.inflate (r.layout.list_item, parent, false); holder.img = (ImageView) Convertview.findviewbyid (r.id.img); Holder.name = (TextView) Convertview.findviewbyid (r.id.name); Holder = new Viewholder (); Convertview.settag (holder); } else{ holder = (viewholder) Convertview.gettag (); } Set holder Holder.img.setImageResource (r.drawable.ic_launcher); Holder.name.setText (list.get (position). partname); Return convertview;}</pre></pre><p><p></p></p><span style="color:#ff0000"><span style="color:#ff0000">3, picture Loading optimization</span></span><br>If the ListView needs to load the display network picture, we try not to load the picture when the ListView is sliding, which will cause the ListView to become stuck, so we need to listen to the ListView state in the listener if the ListView is sliding (scroll_ State_touch_scroll) or be scroll_state_fling, stop loading the picture, or start loading the picture if it is not sliding (scroll_state_idle).<br>If we're going to do it ourselves, Here's a thought.<pre name="code" class="java"><pre name="code" class="java">/** * List scrolling monitor * /listview.setonscrolllistener (new onscrolllistener () { @Override public Void onscrollstatechanged (abslistview view, int Scrollstate) { if (scrollstate = = Onscrolllistener.scroll_state_idle) { List stops scrolling when loading pictures loadimage (startpos, endpos);//loading Pictures asynchronously , loading only pictures you can see } } @Override Public void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int Totalitemcount) { // Sets the starting POS and end POS for the current screen display startpos = firstvisibleitem; Endpos = Firstvisibleitem + visibleitemcount; If (endpos >= totalitemcount) { endpos = totalItemCount-1; }}} );</pre></pre><br>In fact, in the framework of Universal-image-loader this function, and do very well, can be directly used, the code we usually set:<pre name="code" class="java"><pre name="code" class="java">ListView = (listview) Rootview.findviewbyid (r.id.fragment_user_info_lisiview); Listview.setonscrolllistener (displayimageoptionsutil.getpauseonscrolllistener (this)); Listview.setonitemclicklistener (this);</pre></pre><pre name="code" class="java"><pre name="code" class="java">public static Pauseonscrolllistener Getpauseonscrolllistener (onscrolllistener scrolllistener) { Pauseonscrolllistener listener = new Pauseonscrolllistener (imageloader.getinstance (), false, true, scrolllistener); return listener; }</pre></pre><span style="widows:auto">the <span style="widows:auto">first parameter of Pauseonscrolllistener refers to the picture loading object imageloader, The second parameter is pauseonscroll to control whether the picture is paused during sliding, and true if a pause is Required. The third parameter controls the hard sliding interface when the picture is Loaded. </span></span><br>Open the source of pauseonscrolllistener, we can see that<span style="widows:auto">the <span style="widows:auto">Imageloader.pause () method is called when the ListView is sliding or is being jerked.</span></span><pre name="code" class="java">/** * Constructor * * @param imageloader {@linkplain imageloader} instance for controlling * @param pauseonscroll Whet Her {@linkplain imageloader#pause () pause imageloader} during touch scrolling * @param pauseonfling Whether {@linkplain Imageloader#pause () Pause imageloader} during fling * @param customlistener Your custom {@link onscrolllistener} for {@lin Kplain Abslistview list view} which also * would be is get scroll events */public Pauseonscrolllistener ( Imageloader imageloader, boolean pauseonscroll, boolean Pauseonfling,onscrolllistener customlistener) { This.imageloader = Imageloader;this.pauseonscroll = pauseonscroll;this.pauseonfling = PauseOnFling;externalListener = customlistener;} @Overridepublic void onscrollstatechanged (abslistview view, int Scrollstate) {switch (scrollstate) {case OnScrollListener.SCROLL_STATE_IDLE:imageLoader.resume (); break;case Onscrolllistener.scroll_state_touch_scroll: If (pauseonscroll) {imageloader.pause ();} Break;case onscrollListener.SCROLL_STATE_FLING:if (pauseonfling) {imageloader.pause ();} break;} If (externallistener! = Null) {externallistener.onscrollstatechanged (view, scrollstate);}}</pre><br><span style="text-align:justify"><span style="text-align:justify"><span style="color:#ff0000">4, Onclicklistener Processing</span></span></span><span style="text-align:justify"><span style="text-align:justify"> <span style="text-align:justify">When the ListView item has such as button these sub-view, need to set onclicklistener, the usual way is to set in the GetView method, such as</span><br></span></span><span style="text-align:justify"><span style="text-align:justify"><span style="text-align:justify"></span></span></span><pre name="code" class="java"><pre name="code" class="java">Holder.img.setonClickListener (new Onclicklistenr) ...</pre></pre><span style="text-align:justify"><span style="text-align:justify">however, It is inefficient to set a new onclick event each time the GetView is Called. Efficient notation you can set a position directly in viewholder, and then Viewholder implements Onclicklistenr:</span></span><span style="text-align:justify"><span style="text-align:justify"><span style="text-align:justify"></span></span></span><pre name="code" class="java"><pre name="code" class="java">Class Viewholder implements onclicklistener{ int position; TextView name; public void SetPosition (int position) { this.position = position; } @Override public void OnClick (view v) { switch (v.getid ()) { //xxxx } }}public View getView (int position, View convertview, viewgroup parent) { viewholder holder = null; If (convertview==null) { convertview = inflater.inflate (r.layout.list_item, parent, false); Holder = new Viewholder (); Holder.name = (TextView) Convertview.findviewbyid (r.id.name); Holder.name.setOnClickListener (this); Convertview.settag (holder); } else{ holder = (viewholder) Convertview.gettag (); } Set holder holder.name.setText (list.get (position). partname); Set position holder.setposition (position); Return convertview;}</pre></pre><br>Add:<span style="color:#993399"><span style="color:#993399">when the ListView ListItem contains child controls such as a button checkbox, the child controls will grab the focus and the simplest and most effective solution is to set the properties in the ListView item layout file root element to Android: descendantfocusability= "blocksdescendants"</span></span><br><span style="color:#ff0000"><span style="color:#ff0000">5. Reduce the layout level of item View</span></span>This is all layout must follow, the layout level too deep will directly lead to view measurement and painting waste a lot of time<br><span style="color:#ff0000"><span style="color:#ff0000">6, Adapter in the GetView method as little as possible to use logic</span></span>Do not make overly complex logic in the GetView method, and you can find a way to get away from somewhere else, for Example.<span style=""><span style="">pre-optimization GetView ():</span></span><br><span style=""><span style=""></span></span><pre name="code" class="java">@Overridepublic View GetView (int position, view convertview, viewgroup paramviewgroup) {Object current_event = mOb Jects.get (position); Viewholder holder = null; if (convertview = = Null) {holder = new Viewholder (); Convertview = Inflater.inflate (r.layout.row_event, null); Holder. Threedimension = (ImageView) Convertview.findviewbyid (r.id.threedim); Holder. Eventposter = (ImageView) Convertview.findviewbyid (r.id.eventposter); Convertview.settag (holder); } else {holder = (viewholder) Convertview.gettag (); }//here is a logical judgment, which is problematic if (doessomecomplexchecking ()) {holder. Threedimention.setvisibility (view.visible); } else {holder. Threedimention.setvisibility (view.gone); }//this is the parameter that sets the image, which executes this code every time the GetView method executes, which is obviously problematic relativelayout.layoutparams imageparams = new Relativelayo Ut. Layoutparams (measuredwidth, rowHeight); Holder. Eventposter.setlayoutparams (imageparams); Return convertview;}</pre>Optimized GetView ():<span style=""><span style=""></span></span><pre name="code" class="java"><pre name="code" class="java"> @Overridepublic view GetView (int position, View convertview, viewgroup Paramviewgroup) { Object object = Mobjects.get (position); Viewholder holder = null; if (convertview = = Null) {holder = new Viewholder (); Convertview = Inflater.inflate (r.layout.row_event, null); Holder. Threedimension = (ImageView) Convertview.findviewbyid (r.id.threedim); Holder. Eventposter = (ImageView) Convertview.findviewbyid (r.id.eventposter); Setting parameters mentioned here, only the first time will be executed, and then reused relativelayout.layoutparams imageparams = new Relativelayout.layoutparams (measure dwidth, rowHeight); Holder. Eventposter.setlayoutparams (imageparams); Convertview.settag (holder); } else {holder = (viewholder) Convertview.gettag (); }//we use the Getter method of the object directly instead of those logical judgments, and those logical judgments are placed elsewhere to perform the Holder. Threedimension.setvisibility (object.getvisibility ()); return convertview;} </pre></pre><span style=""><span style=""><span style="color:#ff0000">7, Adapter in the GetView method as little as possible time-consuming operation</span></span></span><span style="color:#ff0000"><span style="color:#ff0000"><span style=""></span></span></span><span style=""><span style=""><span style="color:#ff0000">8, Adapter in the GetView method to avoid creating a large number of objects</span></span></span><span style="color:#ff0000"><span style="color:#ff0000"><span style=""></span></span></span><span style="color:#ff0000"><span style="color:#ff0000">9. Set the Scrollingcache and Animatecache of the ListView to False</span></span>These two properties, which are turned on by default, consume a lot of memory and therefore frequently call the gc, and we can turn it off manually (as Appropriate)<br><span style="color:#ff0000"><span style="color:#ff0000">other</span></span><br><span style="color:#000099"><span style="color:#000099">1, Take advantage of the view type, for example, There are several types of Item in your ListView, you need to create a different View for each type, which is advantageous to the collection of the listview, of course, the type can not be too many</span></span><span style="color:#000099"><span style="color:#000099">2, The use of custom view, custom view can effectively reduce the level of Layout, and the drawing process can be very good control;</span></span><span style="color:#000099"><span style="color:#000099">3, as far as possible to ensure that the Adapter hasstableids () returns true, so that in notifydatasetchanged (), if the ID is unchanged, the ListView will not redraw the view, to achieve the purpose of optimization; </span></span><span style="color:#000099"><span style="color:#000099">4, Each Item can not be too high, especially do not exceed the height of the screen, you can refer to the Facebook optimization method, the particularly complex item decomposition into a few small item</span></span><span style="color:#000099"><span style="color:#000099">5, The elements in the ListView to avoid translucency</span></span><span style=""><span style=""><span style="color:#000099">6. Try to turn on hardware acceleration</span></span></span><span style="color:#000099"><span style="color:#000099">7, Use Recycleview instead. The ListView is notifydatasetchanged () every time the data is updated, and some are too violent. Recycleview has been greatly improved in terms of performance and customization, and is Recommended. </span></span><br><br><span style="font-size:24px; color:#ff0000">Take the <span style="font-size:24px; color:#ff0000">time to summarize a bit, while adding some of their own understanding, if there are problems, Welcome to shoot bricks! Little friends, asking for comments ... </span></span><br><br>Reference Link: http://blog.csdn.net/nugongahou110/article/details/47128125http://www.zhihu.com/question/19703384http:// Niorgai.github.io/2014/12/13/listview%e4%b8%8ebaseadapter%e4%bc%98%e5%8c%96/http://www.trinea.cn/android/ android-listview-display-error-image-when-scroll/http://blog.csdn.net/pkxiuluo01/article/details/7380974http:/ /www.w2bc.com/article/45601<br><p><p></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android's Strongest ListView Optimization solution in History</p></p></span>
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