How can I programmatically include layout in Android?

slama007 picture slama007 · Sep 25, 2013 · Viewed 48.4k times · Source

I'm looking for a way to include a layout programmatically instead of using the XML tag include like in my example:

  <include layout="@layout/message"  
           android:layout_width="match_parent" 
           android:layout_height="match_parent" 
           android:layout_weight="0.75"/>

Need to change this parameter "layout="@layout/message" programmatically, please.

Any idea how to do this?

Answer

Kevin Coppock picture Kevin Coppock · Sep 25, 2013

Use a ViewStub instead of include:

<ViewStub
    android:id="@+id/layout_stub"
    android:inflatedId="@+id/message_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.75" />

Then in code, get a reference to the stub, set its layout resource, and inflate it:

ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();