Bobby W Bobby W - 1 month ago 13
Android Question

Android activities, same layout as a template inject different content layout

I was wondering what some of the best practices of achieving this might be.

I'm looking to take a

layout file
that has similiar structure, so I can use it throughout the app in different activities.

So something like this:
activity_base.xml
:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<include
layout="@layout/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>


Is there any way to inject a
layout file
into this include programatically inside of each activity?

So if I have a content file for each activity
content_settings.xml
, inside of
onCreate
or possibly
setContentView
replace
<include />
with the
content_home.xml
resource file.

Answer

You cannot do this with the include tag, but with a ViewStub

A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views. Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub's parent with the ViewStub's layout parameters. Similarly, you can define/override the inflate View's id by using the ViewStub's inflatedId property.

In your scenario you would use setLayoutResource(int) just before you inflate the ViewStub.

Comments