Inflating layout with view visibility changes is an indispensable for every Android developer, When it comes to achieve our goals. To change view visibility , Most of us consider View objects such as GONE,VISIBLE/INVISIBLE. Views with a visibility set to
GONE is bad for performances, especially if the view is a bit complex. Let’s discuss.
Are the “Gone” views inflated?
Yes, They are part of the view hierarchy but are ignored in the rendering passes. It means
onDraw won't get called for the GONE views and it remains children in view hierarchy. To overcome this issue, We may consider to use ViewStub.
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”, I 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.
android:layout="@layout/mySubTree" // layout resource to be inflated
ViewStub stub = findViewById(R.id.stub);
View inflated = stub.inflate();
inflate() is invoked, the ViewStub is replaced by the inflated View and the inflated View is returned to its view hierarchy.
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”.