How many ViewStubs is too many for a single layout XML file?

james picture james · Oct 8, 2010 · Viewed 7.9k times · Source

I have a layout defined in an XML file(base_layout.xml) which may contain 20+ ViewStub definitions in addition to 3-5 other views such an ImageView and a LinearLayout containing 3-5 ImageButton views.

Should i be concerned about how many ViewStub views i place in this layout file?

I read on the developer.android site:

A ViewStub is a dumb and lightweight view. It has no dimension, it does not draw anything and does not participate in the layout in any way. This means that a ViewStub is very cheap to inflate and very cheap to keep in a view hierarchy

is it cheap enough to have 20+ of them? not all being inflated of course, just 1-2 at a time.

when i say cheap enough or talk of being concerned, i am regarding performance of the UI

edit: what i am trying to accomplish: create a layout XML file which can be the skeleton for all my of activities. in each Activity, i will inflate the correct ViewStub with the activity's layout. Since i have so many activities requiring the same skeleton, i wish to re-use as much as possible

I have an Activity class which is the parent of almost all of my activities. this parent class calls setContentView(R.layout.base_layout);. for each child activity, all i am doing is inflating the corresponding ViewStub inside base_layout.xml. doing this allows me to have a very customized UI with the same skeleton view used on all of my activity layouts

Answer

Tseng picture Tseng · Oct 8, 2010

I don't think you'll see a big performance hit. It's still cheaper than having all of them inflated from the begining.

The downside of having so many stubs is that you could lose sight of the whole design. Maybe it makes more sense to group several views/items into one viewgroup. Maybe you could explain what you're attempting to do and see if there is a better way to realize it

edit: Well, instead of having multiple ViewStubs which include different subviews like

<ViewStub android:id="@+id/stub"
           android:inflatedId="@+id/activity1"
           android:layout="@layout/myActivity1"
           />
<ViewStub android:id="@+id/stub2"
           android:inflatedId="@+id/activity2"
           android:layout="@layout/myActivity2"
           />

just have a single ViewStub and in your acitivities onCreate() do something like

setContentView(R.layout.base_layout);
ViewStub stub = (ViewStub)findViewById(R.id.stub);

stub.setInflateId(R.id.activity1);
stub.setLayoutResource(R.layout.myActivity2);
stub.inflate();

This way you'd still have only one ViewStub in your base_layout, which you could setup in code before inflating.