ViewStub in Android

  • getInflatedId() — To get the id taken by the inflated view.
  • setLayoutResources(int layoutResource) — Via this method, we can set the layout resource to inflate when StubbedView becomes visible or invisible or when inflate() is invoked.
  • getLayoutResource() — To get the layout resource that will be used by setVisibility(int) or inflate() to replace this StubbedView in its present with another view. The resultant will be an integer value.
  • inflate() — In order to Inflate the layout resource that gets identified by getLayoutResource() and replace this StubbedView in its parent by the inflated layout resource.
  • setVisibility(int visibility) — Sometimes there is a need to make the visibility to invisible and later on visible.
  • setOnInflateListener(OnInflateListenerinflateListener) — Via this call, It specifies the inflate listener to be notified after this ViewStub successfully inflated its layout resource.

An attribute in ViewStub

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>.



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

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…