The main difference between the two inflate() methods is the second parameter ( ViewGroup parameter) and its use when setting the correct LayoutParams for the root representation of the bloated layout file. This is important because LayoutParams supports various presentation layout attributes (e.g. width, height, positioning rules, etc.) and it is required that the parent of this view can correctly display the view.
The first method basically says: build a hierarchy view from this layout file, but do not assign LayoutParams root of the inflated hierarchy (perhaps because the parent does not know yet), also do not attach a bloated look at the parent.
The second inflation method says: build a hierarchy view from this layout file and also assign the correct LayoutParams (based on the second parameter specified for the inflation method) to the root of the inflated hierarchy , also do not attach the bloated view to the parent.
In the first case, the root file of the bloated layout ( R.layout.childitemlayout ) will not be installed on it by LayoutParams (the inflate method inflate not assigned, since the second parameter is null and it does not know what type of LayoutParams to generate), so your fixed width / height values get lost. Later, when you do mainLayout.addView(childLayout); , mainLayout will check the LayoutParams childLayout , see that it is null , and automatically set the LayoutParams instance (using its generateDefaultLayoutParams() method). This method in the particular case of horizontal LinearLayout returns an instance of LayoutParams where the width / height will be set to WRAP_CONTENT . This way your childLayout will have WRAP_CONTENT as its size, not the fixed values you set.
In the second case, the inflate method sees that you proposed LinearLayout mainLayout as the ViewGroup used to generate LayoutParams . This means that the fixed values (which you used for the width / height) extracted from the layout file can be saved in the corresponding instance of LayoutParams . When you do mainLayout.addView(childLayout); , mainLayout will see that childLayout has its own instance of LayoutParams (which has the values used in the layout file) and does not call generateDefaultLayoutParams() .
source share