ViewStub允许在运行时填充布局资源文件 / A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.

<!-- 占位符, inflatedId 也可以和 id 相同 -->
<ViewStub
    android:id="@+id/stub"
    android:inflatedId="@+id/stubTree"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:layout_alignParentBottom="true"/>
   // 比如,需要在运行时添加一个 Toolbar,需要
   // (1) 在 layout 中添加 ViewStub 作为占位符;
   // (2) 然后在代码中填充 Toolbar 的 layout.

   ViewStub stub = (ViewStub) findViewById(R.id.stub);
   stub.setInflatedId(R.id.stubTree);           // 对应属性字段 android:inflatedId
   stub.setLayoutResource(R.layout.mySubTree);  // 对应属性字段 android:layout
   View inflatedView = stub.inflate();

ViewStub 允许在运行时填充布局资源文件。可以把 ViewStub 理解为占位符,当调用了 inflate() 方法后,从视图层级中移除 ViewStub,android:layout 属性字段定义的布局则被添加到视图层级中,它的 id 是 android:inflatedId。因此这种使用时才填充视图的方式被称作懒汉式 lazily.

如果不需要动态添加替换,则没必要使用 ViewStub,<include layout="@layout/*"/> 就可以解决问题。

Include layout in Android programmatically.

A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. 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(int) or inflate() is invoked. The inflated View is added to the ViewStub's parent with the ViewStub's layout parameters. Similarly, you can define/override the inflate View's id by using the ViewStub's inflatedId property. Copied from http://developer.android.com/reference/android/view/ViewStub.html