Lion Lion - 1 month ago 13
Android Question

Is there any difference between the two methods of inflating a child view?

The first method:

LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, parent, true);


The second method:

LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, null, false);
parent.addView(child);


Is there any difference?

Answer

If You check source of inflate method You will find:

if (root != null) {
     if (DEBUG) {
         System.out.println("Creating params from root: " +
                  root);
     }

     // Create layout params that match root, if supplied

     params = root.generateLayoutParams(attrs);
     if (!attachToRoot) {

         // Set the layout params for temp if we are not
         // attaching. (If we are, we use addView, below)
         temp.setLayoutParams(params);
     }
}

/* ... */

// We are supposed to attach all the views we found (int temp)
// to root. Do that now.

if (root != null && attachToRoot) {
    root.addView(temp, params);
}

So in Your example there is no difference.

There would be a difference in this scenario

View child = LayoutInflator.inflate(context, parent, false);

A child would have same LayoutParams as parent but it wouldn't be attached so it would be just separate view.

Comments