Listview (ViewHolder reuse mechanism) for Android Performance Optimization)
I believe that most people will use the ListView control in many cases, because it is actually a lot of use, but sometimes it gets stuck when there is a lot of data, and when the ListView goes down, this requires us to optimize it.
ListView optimization mainly includes the following aspects:
1. convertView Reuse
2. subview reuse of ViewHolder
3. cache data Reuse
I. convertView Reuse
First, let's talk about the principle of ListView: the Adapter needs to call the getView () method for each Item display in ListView. This method will pass in a convertView parameter, the View returned by this method is the View displayed by this Item. If the number of items is large enough, creating a View object for each Item will occupy a lot of memory space, that is, creating a View object (mInflater. inflate (R. layout. lv_item, null); generate a View from xml, which is an IO operation) is a time-consuming operation, so it will inevitably affect the performance. Android provides a Recycler component, that is, when the ListView Item is out of the screen, the View of the corresponding Item will be cached in the Recycler, correspondingly, an Item is generated, and the convertView parameter in the getView called at this time is the View of the cached Item on the screen. Therefore, if this convertView can be reused, the performance will be greatly improved.
So how can we reuse it? Code:
When convertView does not exist, that is, when it is used for the first time, we create a View object for the item layout and assign it to convertView. When convertView is used in the future, you only need to retrieve the getTag from convertView. You do not need to create the layout object of the item again, which improves the performance.
Ii. Use ViewHolder for Reuse
We all know that the operation in the getView () method is like this: first create a view object from the xml (inflate operation, we used to reuse the convertView Method for optimization), then go to findViewById in this view, find the control objects of the Child View of each item, such as ImageView and TextView. Here, the findViewById operation is a tree search process and time-consuming operation. Therefore, optimization is also required here, that is, ViewHolder is used to place the child View control objects of each item in Holder, when the convertView object is created for the first time, the findViewById of the child View control objects of these items is instantiated and saved to the ViewHolder object. Then, set the viewHolder object to the Tag using the setTag of convertView. When the ListView item is loaded later, you can directly retrieve and reuse the ViewHolder object from the Tag, you do not need to find the child control object of the item in findViewById. This greatly improves the performance.
Paste the complete code: