更新時間: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
好記性不如爛筆頭!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/398026.html
標籤:AI
上一篇:adb網路除錯
下一篇:Android include
