ViewStub: On-demand inflate view or lazily inflate layout resource

Sometimes while developing an application, we have encountered a situation like based on some logic, we have to render some new view in the layout that is rarely used. A general approach for this is to make View visibility GONE/VISIBLE.
So always inflating this rarely used view in a layout, is not a good idea and also it impacts the rendering of the layout.
So what to do in this case?
So we have ViewStub for this.
What is 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. It does not participate nor draws anything in the layout.
When to use ViewStub?
- When you want to inflate view lazily i.e on-demand or at runtime based on some logic.
- When you don't want to render rarely used UI in layout always.
Benefits of ViewStub:
- This can reduce memory usage and speed up rendering by loading the views only when they are needed.
- Get rid of View GONE/VISIBLE
ViewStub vs Include Tag
Include tag will just include the XML content’s in your layout.
ViewStub will be loaded only when you actually need it i.e when you set ViewStub visibility to true or call inflate() then only it will draw on UI.
How ViewStub works :
- When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated.
- The ViewStub then replaces itself in its parent with the inflated View or Views. Therefore, the ViewStub exists in the view hierarchy until setVisibility or inflate() is invoked.
- The inflated view is added to the ViewStub's parent with the ViewStub's layout parameters.
How to use ViewStub in Android :
- id: ViewStub defined can be found using the id.
- inflatedId: This attribute is used to set the id of the inflated View.
- layout: This attribute is used to supply an identifier for the layout resource to inflate.
When inflate() is invoked, the ViewStub is replaced by the inflated View and the inflated View is returned to its view hierarchy.
Reference:
https://developer.android.com/reference/android/view/ViewStub.html
https://medium.com/@sekarmohan77/android-viewstub-b03373ecf03a

Thanks for reading. Soon I will post more articles on Android and core Java.
Till then happy learning and keep reading!
You could check out my other interesting topics here.