Difference between and in and

2019-02-11 23:13发布

问题:

What are the differences between <\include> tag and <\ViewStub> tag and which one is preferrable while designing the layout.

Thanks,
venu

回答1:

The < include /> will just include the xml contents in your base xml file as if the whole thing was just a single big file. It's a nice way to share layout parts between different layouts.

The < ViewStub /> is a bit different because it is not directly included, and will be loaded only when you actually use it/need it, ie, when you set its visibility to VISIBLE (actually visible) or INVISIBLE (still not visible, but its size isn't 0 anymore). This a nice optimization because you could have a complex layout with tons of small views or headers anywhere, and still have your Activity load up really fast. Once you use one of those views, it'll be loaded.



回答2:

  • include
    It is used to reuse layout resource
  • ViewStub
    It is used to lazily inflate layout resource


回答3:

Sharing and reusing layouts is very easy with Android thanks to the tag, sometimes even too easy and you might end up with user interfaces that contain a large number of views, some of which are rarely used. Thankfully, Android offers a very special widget called ViewStub, which brings you all the benefits of the without polluting your user interface with rarely used views.

A ViewStub is a dumb and lightweight view. It has no dimension, it does not draw anything and does not participate in the layout in any way. This means a ViewStub is very cheap to inflate and very cheap to keep in a view hierarchy. A ViewStub can be best described as a lazy include. The layout referenced by a ViewStub is inflated and added to the user interface only when you decide so.



回答4:

Another important difference is related to layout inflating. with it is not possible to change the layout already static inflated in XML, it is necessary to replace the view and set programmatically al the layout parameters. With it is possible to define (for e.g.) height, width, etc... and inflate different layout at runtime time