ViewStub Example And Use In Android

A ViewStub is a dumb and lightweight view which has no dimension It does not draw anything and does not participate in the layout in any way. This means a ViewStub is very cheap to inflate and very cheap to keep in a view hierarchy. A ViewStub can be best described as a lazy include. The layout referenced by a ViewStub is inflated and added to the user interface only when you decide so.

The difference between ViewStub and include tag:
The include tag will just include the xml contents in your base xml file. It’s a nice way to share layout parts between different layouts.The ViewStub tag is a bit different because it is not directly included, and will be loaded only when you actually need it, i.e, when you set it’s visibility to “true”. This a nice optimization because you could have a complex layout with tons of small views or headers anywhere, and still have your Activity load up really fast. Once you use one of those views, it’ll be loaded.

In the example below we will see a very simple ways to work with various implementations of ViewStub class from Android platform. We will create a screen with two buttons and a third component as a message dialog to pop-up on screen rather than a separate screen, and to dissapear on another user action. So one button on click shows this message and another button just hides it.

Algorithm:

1.) Write following into MainActivity.java:

 

 

 

Here in above code the onClick method has a condition to check whether ID of the component matches
and accordingly set the visibility factor for the viewstub.

2.) Create and write following into ViewStubButton.java

 

 

 

3.) Write following into activity_main.xml:

 

 

 

The view stub class file above uses below layout as drawable.

4.) Create and write following into overlay_layout.xml

 

 

 

Output:

viewstub1

Now lets try to create very simple example of showing a ViewStub with a different layout XML file. This example will have a Activity with a layout XML file, which contains a ViewStub, while ViewStub has another layout that inludes a ScrollView and a TextView in it. We will use inflate method of ViewStub to inflate secondary Layout XML
file.

1.) Write following into your manifest file:

 

 

 

2.) Write following into activity_example_view_stub.xml

 

 

 

3.) Write following into example_layout.xml

 

 

 

4.) Write following into ViewStubActivity.java