我们在使用include
的时候给被引入的布局添加一个id
,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/titleBar"
layout="@layout/titlebar" />
...
</LinearLayout>
merge
和include
最大的区别在于,使用merge
标签引入的布局在某些情况下可以减少一层布局的嵌套,而更少的布局嵌套通常就意味着更高的效率。
比如说我们对某.xml进行如下修改:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Back" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Title"
android:textSize="20sp" />
<Button
android:id="@+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Done" />
</merge>
可以看到,这里最外层的布局使用了merge
标签,这就表示当有任何一个地方去include
这个布局时,会将merge
标签内包含的内容直接填充到include
的位置,不会再添加任何额外的布局结构。
但是很遗憾,如果使用这种写法的话,运行程序将会直接崩溃。因为merge标签并不是一个布局,所以我们无法像刚才那样在include
的时候给它指定一个id
。
那么这种情况下应该怎么使用ViewBinding呢?首先为了避免崩溃,我们应该将activity_main.xml中引入布局时指定的id移除,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/titlebar" />
</LinearLayout>