Include VS ViewStub VS Merge

10 Mar 2023 . android .

Reuse other layouts.

Delete redundant levels and optimize UI.

Use include

layout1.xml

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml

<FrameLayout>
   <TextView />
</FrameLayout>

It actually looks like:

<FrameLayout>
   <FrameLayout>
      <TextView />
   </FrameLayout>
</FrameLayout>

Use merge

layout1.xml

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml

<merge>
   <TextView />
</merge>

It actually looks like:

<FrameLayout>
   <TextView />
</FrameLayout>

An invisible view with 0 height and 0 width. Loading of this view has been delayed to optimize UI rendering. Only take a placeholder when first rendering.