ViewStub in Android

Most of the time we are using <include> to inflate other XML files in the main XML. but it will always cost us heavy use of CPU and battery.

what if we can have something which will inflate when we request?

let's explore ViewStub…

A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.

It is a dumb and lightweight view and it has zero dimension

It is used to lazily inflate layout resource. The <ViewStub> views are inflated on call.

When the ViewStub is inflated, it replaces itself in its parent view with the inflated layout resource. Its visibility will exist in the view hierarchy only when setVisibility(int) or inflate() is invoked.

The inflated view is added to ViewStub’s parent using the layout parameter.

We can use ViewStub in the following places, for example — progress Indicators, undo messages, some item details etc.

It reduces memory usage and speeds up rendering by loading the views only when they are needed.

Method availability in ViewStub

An attribute in ViewStub

id — To uniquely identify a ViewStub

inflated — To set the ID of the inflated View. we can set it by using the setInflatedId() method.

layout — To supply an identifier for the layout resource to inflate when the ViewStub becomes visible or when forced to do so.

we can be set by using the setLayoutResource(int) method.

ViewStub vs Android <include>

The < include /> will just include the XML contents in our base XML file as if the whole thing was just a single big file. It’s a nice way to share layout parts between different layouts.

The < ViewStub /> is a bit different because it is not directly included, and will be loaded only when you actually use it/need it.

The benefit of the <ViewStub> is we can have a complex layout with tons of small views or headers, and still have our activity load up really fast. Once we use one of those views, it’ll be loaded.

The loading of ViewStub is must faster than <include> views. For example, if we have 100+ <include>views takes 80 times more CPU time than 100+<ViewStub>.

The battery power consumption is more with <includes> as compare to <ViewStub>.

Happy coding…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prachi Mishra

I am an Android Developer. Working for BMW group. In my development path if I find something interesting I like to share with you guys. Happy coding…