Android: Programmatically make layouts from XML

android, android-layout

Solution

You can do that with the LayoutInflater service. Get a reference to it by loading it like this:

LayoutInflater inflater =
    (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then you can create a layout from an XML resource like this:

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

The `layoutname` here is simply the name of the XML file in your `res/layout` directory.

Finally you can add this view to your layout using the `addView` function.

Problem

I have a generic layout in XML I would like to programmatically add after filling it with content (i.e. change the text on a text view, set a listener for a button, etc.) multiple times to a on-screen layout. I know I can add Views using layout.addView(View V), but how do I construct a new layout from an XML file?

Original source