更新时间:2021-12-29
通过merge可以消除视图层次结构的冗余;
merge标签必须使用在根布局;
对merge标签设置的属性是无效的。
1. 使用方式示例
1)创建一个layout,如:my_merge_layout.xml
<?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="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 2"
/>
</LinearLayout>
2)通过include引入上方的布局
在 activity_main.xml中通过include使用布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="this is button"
/>
<include layout="@layout/my_merge_layout" />
</LinearLayout>
3)效果如下
可以看出,LinearLayout中,又嵌套了一个LinearLayout
(Android布局层次结构查看工具-Layout Inspector介绍:https://blog.csdn.net/cadi2011/article/details/85212762)
4)对my_merge_layout.xml进行修改,将LinearLayout替换为merge
这里对merge设置了属性,其实这里的属性是不会生效的!
通过include引入,系统会忽略merge并直接布局里面的两个按钮,以代替include。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 2"
/>
</merge>
5)修改后效果如下
通过merge可以减少布局嵌套。
修改后,没有了多个LinearLayout嵌套了。
2. 参考文档:
Merge介绍:
https://developer.android.google.cn/training/improving-layouts/reusing-layouts?hl=en#Merge
Android布局层次结构查看工具-Layout Inspector介绍:
https://blog.csdn.net/cadi2011/article/details/85212762
好记性不如烂笔头!