While developing an application we have encountered situations like displaying a view based on some logic, for example we need to render an image map when the button is tapped as shown below
How can we handle this case?
A common approach to this is to create a group of views and change the visibility programmatically, or we can make them more readable by breaking the group of views into a new XML layout and then tagging that
An invisible or vanished view does not mean that it is not inflated
If we set the view as invisible or disappeared, the view will not be rendered, which means
onDraw is not invoked, but the view is still inflated due to part of the view hierarchy. Then how can we inflate the view when needed?
ViewStub meets our needs
A ViewStub is an invisible, zero-sized view that can be used to lazily inflate layout resources at runtime. This is very interesting because ViewStub doesn’t participate in the layout, doesn’t draw anything and has no dimension. When working with complex layouts, sometimes we need to display certain layout components based on multiple conditions, for example we have a component to display an ad banner that contains text and a button because this ad banner is seasonal and not always available.
In this state, we can use ViewStub to solve these cases.
General ViewStub Attributes
Like others’ views, ViewStub has some commonly used attributes:
- I would: Defined ViewStubs can be found with these attributes
- inflated ID: Set the ID of the inflated layout
- Layout: These attributes are used to provide an identifier for the layout resource to inflate, you can also set them programmatically.
You can use a ViewsStub and then inflate it with another layout component based on the condition.
How to inflate ViewStub
You can create a new lazy variable inflation() the ViewStub and call it when needed.
When inflate is called, the viewstub is replaced with the layout view inflate, and the inflated view returns to the view hierarchy.
Access to the bloated layout view
We know how to inflate the layout, and then how can we access the view from the inflated layout? We can use view binding to achieve this case
- Create a new latinit variable to store our inflated layout view binding
- When the layout is created, listen to the inflate listener from our ViewStub and then initialize our inflated layout view binding
- Finally, we can access the Inflate part of the layout using its ID
Congratulations, you learned new things about ViewBinding in Android 🎉. You can learn more about ViewBinding on the Android official developer site.