Android layoutinflator.inflate source code analysis

Detailed explanation of layoutinflator.inflate source code

It is believed that we are familiar with the expand method of layoutinflator. We often use this method to instantiate the view we need in oncreateview of fragment or getview method of baseadapter

Suppose we have a layout file menu that needs to be instantiated_ item.xml:

We want to instantiate it in the getview () method of baseadapter. There are three instantiation methods, namely:

Method of 2 parameters:

Method with 3 parameters (attachtoroot = false):

Method with 3 parameters (attachtoroot = true):

Which method should we use to instantiate view, and what is the difference between the three methods? If some students are not particularly clear about the difference between the three methods, then join me to analyze this problem from the perspective of source code

Source code

inflate

Let's first look at the inflate method with two parameters. The source code is as follows:

From the code, we can see that the inflate method of the two parameters actually calls the inflate method of the three parameters according to whether the parent layout parent is null as the third parameter. The source code of the inflate method of the three parameters is as follows:

Here, we need to explain that the resource layout ID we passed in cannot be instantiated directly. We need to use xmlresourceparser

The xmlresourceparser parses the layout file with the pull parsing method of Android. Continue to track the source code of the inflate method:

I have added Chinese comments to the key parts of the above code. From the above code, we can also find that the layout file we passed in instantiates each child node through createviewfromtag

createViewFromTag

The source code of the function is as follows:

In the createviewfromtag method, the view control is instantiated by reflection through the createview method

createView

summary

After learning the source code of the inflate function and looking back at the three methods of baseadapter, we can draw the following conclusion:

The use of the first method is not standardized, and will cause the layoutparams property of the instantiated view to become invalid. (PS: that is, the parameters such as layout_width and layout_height become invalid, because the layoutparams in this case in the source code is null)

The second is the most correct and standard way of writing

Third, because attachtoroot is true, the returned view is actually the parent layout listview, which is obviously not the view we want to instantiate. Therefore, the third writing method is wrong

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>