Start a Project

How layoutinflator works at runtime

There is common issue that people including me faces. The issue is why does LayoutInflater ignore the layout parameters that I’ve specified?

E.g. why are the layout_width and layout_height values from my resources XML not honored?

The following tutorials shows how to dynamically populate a layout using LayoutInflater.

Before we get started see what LayoutInflater.inflate() parameters look like:

Now for the sample layout and code.

Main layout (main.xml):

Added into this container is a separate TextView, visible as small red square if layout parameters are successfully applied from XML (red.xml):

 

Now LayoutInflater is used with several variations of call parameters

 

The actual results of the parameter variations are documented in the code.

SYNOPSIS: Calling LayoutInflater without specifying root leads to inflate call ignoring the layout parameters from the XML. Calling inflate with root not equal null and attachRoot=truedoes load the layout parameters, but returns the root object again, which prevents further layout changes to the loaded object (unless you can find it using findViewById()). The calling convention you most likely would like to use is therefore this one:

 

Exit mobile version