布局准备
test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test"
android:textColor="@android:color/black"
android:textSize="13sp" />
</LinearLayout>
1.include使用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test_include"
android:textColor="@android:color/black"
android:textSize="13sp" />
<include layout="@layout/test" />
</LinearLayout>
页面会直接展示出垂直方向的文字:
test_include
test
2.merge使用
test_merge.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test_merge"
android:textColor="@android:color/black"
android:textSize="13sp" />
</merge>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test_include"
android:textColor="@android:color/black"
android:textSize="13sp" />
<include layout="@layout/test_merge" />
</LinearLayout>
页面会直接展示出垂直方向的文字:
test_include
test_merge
merge使用注意点:
- merge必须放在布局文件的根节点上,对merge设置的所有属性都无效
- merge并不是一个ViewGroup,也不是一个View,它相当于声明了一些视图,等待被添加。
- 因为merge标签并不是View,所以在通过LayoutInflate.inflate方法渲染的时候,第二个参数必须指定一个父容器,且第三个参数必须为true,也就是必须为merge下的视图指定一个父亲节点。
- merge标签被添加到父容器后,merge下的所有视图将被添加到父容器下,即merge下所有视图都会遵循父容器的布局规则
3.ViewStub
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test_view_stub"
android:textColor="@android:color/black"
android:textSize="13sp" />
<ViewStub
android:id="@+id/vs_test"
layout="@layout/test"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
页面在预览时候仅会展示出test_view_stub,不会展示test。
ViewStub viewStub = findViewById(R.id.vs_test);
if (viewStub != null) {
//viewStub.setVisibility(View.VISIBLE);
View inflated = viewStub.inflate();
View view = inflated.findViewById(R.id.tv_test);
}
代码中执行完 viewStub.inflate() 或 viewStub.setVisibility(View.VISIBLE) 后,ViewStub标签下的布局才会显示出来,viewStub.inflate()不执行,页面不会展示也不会绘制ViewStub标签下的布局。