Android AdapterView source code analysis and analysis of related collection mechanisms

Source: Internet
Author: User

Preface

Suddenly, I found that the public information on the Internet is to teach you how to inherit a baseadapter, then rewrite the several methods, then call the setAdpater () method of the relevant view, and then, your item is displayed on the mobile phone screen. Few people are concerned about the implementation principle of the android adpater mode mechanism. What is more in-depth is the recycling situation in adapter getview. Today, I read the relevant source code and recorded my understanding.

AdpaterView Overview

AdpaterView

Api manual Description: An AdapterView is a view whose children are determined by an Adapter.

In fact, the ListView, GridView, Spinner, Gallery, and other views in android are implemented based on the Set Topology mode in the design mode. As long as you are familiar with the related knowledge of the Set Topology mode, you will know how to find relevant implementation clues from the source code.

Understanding AdapterView

Source code link https://github.com/android/platformFrameworksBase/blob/master/core/java/android/widget/AdapterView. java

To understand the implementation of listview and so on, its parent class has to be viewed. The source code contains more than 1200 Lines. After reading AdapterView, you can understand the following issues:

  1. Responds to data changes.

    793-842)

  2. When you click view, you can obtain the corresponding position.

    593-615)

Respond to data changes

Assume that you have opened lines 793 to 842 of AdpaterView ..

When I first started using adapterview, what made me the most effort was: why can I update the view status by calling the notifyDataSetChanged () command of adpater, and then call yydatasetinvalidated () what is the difference between the two? In the past, I found some information and did not find a detailed description. Now, if I find the answer from the source code, it is very clear.

First, we need to understand a design pattern: observer design pattern.

I believe that you should be able to understand what the observer mode is like...

AdapterView responds to the data update of the Adapter because it registers an internal class of the Data observer AdapterDataSetObserver (793-842) on the Adapter. Therefore, we only need to send a notification to change the adpater status, so that AdapterView can call the corresponding method.

DataSetObservable source code. Remember to read its parent class. Https://github.com/android/platformFrameworksBase/blob/master/core/java/android/database/DataSetObservable. java

Now we can solve our first question: what is the impact of returning notifyDataSetChanged () and notifyDataSetInvalidated () back to AdapterView?

Let's compareonChange()AndonInvalidated()The former synchronizes the status of the current location, and the latter resets the status of all locations. You can also obtain more information from the code comments.

In this way, we will call yydatasetchanged () and notifyDataSetInvalidated () to better understand what will happen.

How can I obtain the current position by clicking item?

Assume that you have opened the 593-615 rows of AdpaterView ..

ForgetPositionForView()You have never used this method. To understand why we can obtain the position of the item view in adapterView, we need to see its direct subclass: AbsListView. class.

Source code: 2130-2197) 2196-2279)

Here we use another design mode: Delegation mode.

Suppose you have understood the concept of delegation mode. First, let's look at source code 2130-2197 ).

SlaveobtainView()We can know in the method name that this is a method used to generate itemView. After reading this piece of code, will there be any questions in the future? Don't worry about recycling the piece first )?PositionWhere is it? We can see that this method does not actually set any listener for our itemview. Why can we finally respond to our itemview action?

Next let's take a look: source code 2196-2279)

From the code, we can see that this is a delegate class that initializes the actions of items and responds to corresponding operations. From the source code, we can find out why an item view can be clicked, longclick, select action to respond, then, by callingperformItemClick()Finally call the event to the AdapterView292-303)performItemClick()Listener method.

If you are not familiar with the delegation mode, it may take some time to understand it.

Understanding AbsListView recycling mechanism

Source code: AbsListView. class

For a long time, there has been such a saying that listview will automatically recycle invisible views, but for a long time, I have not seen any analysis on its recycling mechanism.

Recycling executor: RecycleBin

Let's go back to the previously viewed AbsListView. class

obtainView()2130-2197)

You will see

mRecycler.

Next, we can find that the variable is initialized in 308) by searching. This is an internal class

RecycleBin instance 6139-6507)

We can see that this class is the implementer of the absListView recycling mechanism.

Please jump to 6139)

Now, let's take a look at The comments of this class. This class is used to help reuse The view. It stores The RecycleBin has two levels of storage in two different levels) I personally think the description is quite awkward. I 'd better read the original text ..)

  1. ActiveViews: view displayed on the screen at the beginning

  2. ScrapViews: some potential old views that can be used by adpater.

Then, the comment says, how does ActiveViews become ScrapViews. We have two questions about the provided information.

  1. When ActiveViews are generated.

  2. When to generate ScrapViews.

These two points should be clarified, and the entire recycling system will be clear.

Specific implementation of the AbsListView recycle Mechanism

From the RecycleBin class comment, we know that the first step of the recycling mechanism is to place the screen view in ActiveViews, and then downgrade ActiveViews to ScrapViews, and reuse the view through scrapViews.

Through some searches, we find in Listview. class (row 1562fillActiveViews()).

Let's take a look at Listview. class1460-1713 ).layoutChildren()Why is this method used.

When we see rows 1550), we will find the value assignment of this recycle class. Next, let's take a look at how listview uses the recycling mechanism:

  1. When the data changes, place the current view in scrapviews; otherwise, mark it as activeViews1557-1562)

  2. recycleBin.removeSkippedScrap();Remove all old views

  3. recycleBin.scrapActiveViews();Refresh the cache and move the current ActiveVies to ScrapViews.

What have you done here? We will return to 1557-1562). We can see a variable dataChanged. From the meaning of a word, we can see that the optimization rule here is based on whether the data has changed. We can search for a member variable by searchingmDataChangedIn (1693), it turns to false. Then wemakeAndAddView1751-1775) found the use of this variable.

Read 1756-1766). We can see the first use of the recycle mechanism. If the data does not change, check whether the current active view exists in the ActiveViews (these views are from 1557-1562) list, if yes, reuse the existing view directly. The advantage is that the existing view is reused directly, and the subview does not need to be obtained through adapter. getview.

Okay. Let's take a look.makeAndAddView1751-1775) How to passadapter.getview()View. Let's go back to AbsListView. class2130-2194)

In 2134), we can see a mysterious method.scrapView = mRecycler.getTransientStateView(position);From the meaning of the word, we can know that this is to get a view of the instantaneous state. Here is a question about what is the instantaneous view? Through layer-by-layer analysis of the source code, we finally find the description in the hasTransientState () method of the View class. We know from the description that this method is used to mark the instantaneous state of the view, to tell the app not to care about its storage and recovery. In the comments, the official team told me that this kind of view with instantaneous state is used in view animation playback and other situations.

We can understand that this sentence optimizes the list animation of absListView.

After reading the code, I am confused.

scrapView = mRecycler.getScrapView(position);

From this line of code, we can see that the reused review is related to the location. Let's go back and look at it (ListView 1557-1563)

       if (dataChanged) {            for (int i = 0; i < childCount; i++) {                recycleBin.addScrapView(getChildAt(i), firstPosition+i);            }        } else {            recycleBin.fillActiveViews(childCount, firstPosition);        }

We can find that only the currently displayed view is put in the recycle class, and no view is generated for the current screen. However, in actual use, when we perform screen scrolling, when the next view is displayed, we can see that the second parameter of getView is no longer null. Where is the actual implementation? We can find it by searching for the RecycleBin method.

layoutChildren()

scrollListItemsBy()

onMeasure()

measureHeightOfChildren()

View

scrollListItemsBy()

We can understand that when we perform screen scrolling, we put the removed item view into the listview when removing the item view.

recycleBin.addScrapView(last, mFirstPosition+lastIndex);

So the previous view can be reused when the next view is generated. After figuring out this mechanism, we will return

AbsListView. class2139-2168)

The following code explains the source of a classic adapter optimization method.

  View child;    if (scrapView != null) {        child = mAdapter.getView(position, scrapView, this);
        if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {            child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);        }        if (child != scrapView) {            mRecycler.addScrapView(scrapView, position);            if (mCacheColorHint != 0) {                child.setDrawingCacheBackgroundColor(mCacheColorHint);            }        } else {            isScrap[0] = true;            child.dispatchFinishTemporaryDetach();        }    } else {        child = mAdapter.getView(position, null, this);        if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {            child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);        }        if (mCacheColorHint != 0) {            child.setDrawingCacheBackgroundColor(mCacheColorHint);        }    }

In fact, the so-called optimization is to reuse existing views to reduce the class instantiation in Adapter. getView () to optimize the performance.

From the google io documents of a year, we learned that the efficiency of this collection mechanism can provide listview 300% efficiency.

Then we understand

GetView (int position, View convertView, ViewGroup parent) is the origin of the three parameters.

Through the analysis of the recycling mechanism, we can view

Listview scrollListItemsBy ()

In fact, invisible items are automatically removed. Why is oom occurring when too many items are rolled?

When we read the complete recycle mechanism, we will find that the recycle mechanism actually caches the view object in the memory so that the listview can quickly obtain the view to make the display of the listview smooth. The OOM problem also exists here. Because the entire recycle mechanism saves bitmap objects in all imageviews, The RecycleBin class is getting bigger and bigger during ongoing screen sliding operations, eventually, OOM occurs.

Of course, to avoid OOM, we only need to create a memory block in the virtual machine to save the map object of bitmap objects, which is generally implemented using the LRU algorithm ), all imageview applications reference the entire map object. When the map object is larger than a certain degree, some bitmaps are released, which ensures that RecycleBin saves these imageviews, the bitmap objects in these imageviews are obtained through a fixed memory block, as long as the size of the memory block we opened for the referenced bitmap is reasonable, in this way, oom will never happen.

The recycler of other views inherited from AbsListView is the same ..

Feelings

It took a few hours to read the relevant source code of AdapterView, and roughly lines of code were calculated. Of course, it would not be a line of code. Here is a method for viewing the source code. First of all, where there are interfaces and abstract classes, all methods must be fully viewed. This part is basically a line of review. In fact, these interfaces and abstract classes are important indexes of the source code. The 4-and 5-K lines of code are actually the key interfaces and the extensions of the corresponding abstract classes.

This article is from the "game a chai" blog, please be sure to keep this source http://youxilua.blog.51cto.com/3357586/1197715

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.