Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Programmatically make layouts from XML

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?

like image 721
Flynn Avatar asked Sep 09 '26 19:09

Flynn


1 Answers

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.

like image 55
Overv Avatar answered Sep 11 '26 09:09

Overv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!