Gaurav Agarwal
Gaurav Agarwal

Reputation: 19102

What happens behind the scenes when an xml is "inflated"?

For example When we write the code

View view = inflater.inflate(R.layout.main_activity, null);

What does the Android system do?

Upvotes: 1

Views: 380

Answers (2)

Simon
Simon

Reputation: 14472

Check out the source for the LayoutInflater. It's an abstract class, a concrete instance of which is obtained through getLayoutInflater().

In essence, the inflater creates a root view object (the root view group of the inflated XML), then does two passes through the XML tree to attach each child view. This is done recursively to handle 'include' and to fix up references between child views, for example in RelativeLayout, and is done top to bottom.

The first pass constructs the tree by instantiating each of the child views, top down recursively, and passes the XML attributes to the view constructor telling the view how big it should be. It then calls measure() for each child passing in restrictions determined by the parent (e.g. RelativeLayout with 2 child views each requesting match_parent) using a measure specifications object and asks the view how big it wants to be. If the view is itself a view group, it will use the same algorithm to measure it's children.

The second pass is the layout pass when layout() is called on each child to position itself within the view. The parent positions the view using the measurements calculated in the measure pass. onDraw() is called and is passed a Canvas created from the DecorView backing bitmap.

The finalised tree is then ready to pass to the window manager which is done by setContentView() or addContentView().

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/view/LayoutInflater.java#LayoutInflater

Upvotes: 4

Lalit Poptani
Lalit Poptani

Reputation: 67296

Inflating an XML layout in simple language means you are converting the XML in View. Then you can fetch each view declared in the XML using the parent/inflated View.

For eg -

View view = inflater.inflate(R.layout.main_activity, null);

Now, here view is the reference of the XML from which you can fetch all the views as,

TextView tv = (TextView)view.findViewById(R.id.tv);

Upvotes: 0

Related Questions