In Android, ViewStub is zero sized invisible View that can be used to lazily inflate layout resource at runtime. It is a dumb and lightweight view. The special thing about ViewStub is that it neither participate nor draw anything in the layout. It has zero dimension.
By term inflate we mean load the layout resource at runtime and then ViewStub replace itself in its parent by the inflated layout resource.
Layout referenced by a ViewStub is inflated and added to the UI only when we decide. It means Whenever a ViewStub is made visible, or when inflate() method invoked, the layout resource is inflated and then ViewStub replaces itself in its parent with the inflated Resource. The ViewStub only exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub’s parent using layout parameter.
Sometimes our layout might require complex views that are rarely used. Whether they are item details, undo messages, or progress indicators. You can reduce memory usage and speed up rendering by loading the views only when they are needed.
Difference between ViewStub and include tag:
The include tag will just include the xml content’s in your xml file. It’s a nice way to share layout parts between different layout’s. The ViewStub tag is a little bit different because it is not directly included, and will be loaded only when you actually need it, i.e when you set ViewStub’s visibility to “true”.
This is a nice optimization because you could have a complex layout with tons of small views, complex views or headers anywhere, and still have your Activity load up really fast. Once you use one of those views, it’ll be loaded.

Share with your friends:

Leave a comment

Your email address will not be published. Required fields are marked. *