Whats the point of ViewStub when I can also lazily inflate a view without it?

android

Solution

The basic use of `ViewStub` is to act as a "placeholder" to an element that won't be needed at a later time without taking additional upfront performance load. Now, your question why not just inflate it dynamically then?

They serve both purposes the same, only that when using a `ViewStub`, you separate and already define the all of your UI in a separate XML, so it's a separation of concerns. Now if you've got a dynamic UI, then it would be better to go programmatically inflating your UI.

So all in all,

defined UI: prefer `ViewStub`

dynamic UI: prefer programmatically inflating `Views`

As for my experience, I've used it for a project I've had to maintain and needed to overcome a complex hierarchy of `Views`, which took too long to load. `ViewStub` helped in lazy loading a defined UI, improving the start-up of the UI.

Problem

After reading the docs, I'm not sure what ViewStub accomplish that I cannot with creating a XML with a View and then inflating it at run time. The Doc says use ViewStub to inflate views at run time. I'm not sure why this is useful other than syntax is a little easier. Or am I totally wrong about this?

Original source