Android: programmatically create layouts from XML

I have a general layout in XML that I would like to programmatically add after filling it with content (i.e. change the text in the text view, set the listener for the button, etc.) several times on the screen layout. I know that I can add views using layout.addView (View V), but

How do I create a new layout from an XML file?

+3
source share
1 answer

You can do this using the LayoutInflater service. Get a link to it by downloading it as follows:

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

Then you can create the layout from the XML resource as follows:

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

layoutnamehere is just the name of the xml file in your directory res/layout.

, , addView.

+12

All Articles