slama007
slama007

Reputation: 1293

How can I programmatically include layout in Android?

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?

Upvotes: 81

Views: 63543

Answers (4)

AI Shakil
AI Shakil

Reputation: 1732

ViewStub Kotlin Implementation

Inside your onCreate function:

val viewStub: ViewStub? = binding?.viewStub
viewStub?.layoutResource = R.layout.your_layout

if (viewStub?.parent != null) {
    viewStub.inflate()
}

Don't forget to comment for any inquiries

Upvotes: 1

Daniele D.
Daniele D.

Reputation: 2734

In Mono.Droid / Xamarin this worked for me:

ViewStub stub = FindViewById<ViewStub>(Resource.Id.layout_stub);
stub.LayoutResource = Resource.Layout.whatever_layout_you_want;
stub.Inflate();

Upvotes: 3

patel135
patel135

Reputation: 927

ViewStub stub = (ViewStub) findViewById(R.id.text_post);
        stub.setLayoutResource(R.layout.profile_header);
        View inflated = stub.inflate();

Upvotes: 6

Kevin Coppock
Kevin Coppock

Reputation: 134664

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();

Upvotes: 180

Related Questions