Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
slama007 Avatar asked Sep 25 '13 08:09

slama007


People also ask

Which function is used to include layout to an activity in android?

Use the <include> tag However, if you want to override layout attributes using the <include> tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect.

Is it possible to include one layout definition in another?

Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.


2 Answers

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(); 
like image 150
Kevin Coppock Avatar answered Sep 19 '22 02:09

Kevin Coppock


ViewStub stub = (ViewStub) findViewById(R.id.text_post);         stub.setLayoutResource(R.layout.profile_header);         View inflated = stub.inflate(); 
like image 42
patel135 Avatar answered Sep 18 '22 02:09

patel135