Bobby W Bobby W - 1 year ago 67
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:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent" />

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
, inside of
or possibly
<include />
with the
resource file.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download