Android 提供豐富的基礎 Widget,但實際專案常需組合成更高階的 UI 模組(如:標題列、載入狀態、確認對話框)。透過 <include> 標籤,我們能在 XML 中像引用函式一樣重用佈局,減少重複代碼、統一風格、提升維護性。
| 屬性 | 必要性 | 說明 |
|---|---|---|
layout | ✅ 必填 | 引用的佈局資源 ID(如 @layout/toolbar_common),不帶 android 前綴。 |
android:id | 選填 | 覆蓋被引用佈局根 View 的 ID,便於 findViewById 區分多實例。 |
android:layout_* | 選填 | 可覆蓋任意佈局參數(寬、高、margin 等),寬高必須成對覆蓋否則無效。 |
res/layout/toolbar_common.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
在 Activity 佈局中引用三次
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/toolbar_top"
layout="@layout/toolbar_common" />
<!-- 中間內容 -->
<include
android:id="@+id/toolbar_bottom"
layout="@layout/toolbar_common"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<include
android:id="@+id/toolbar_float"
layout="@layout/toolbar_common"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="16dp" />
</LinearLayout>
若被引用佈局的根 View 只是容器(如 FrameLayout),可改用 <merge> 避免多餘巢狀:
<!-- res/layout/item_user.xml -->
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<ImageView android:id="@+id/iv_avatar" ... />
<TextView android:id="@+id/tv_name" ... />
</merge>
引用時:<include layout="@layout/item_user" /> —— 產生的 View 會直接掛在父容器下。
res/layout/activity_main.xml:主框架,<include layout="@layout/content_main" />res/layout-land/content_main.xml:橫屏專用內容res/layout-port/content_main.xml:直屏專用內容如此一來,主框架只維護一份,內容隨裝置方向自動切換。
layout_width 不設 layout_height 會導致屬性失效,繼承原佈局值。<include> 同一資源時,必須指定不同 android:id,否則 findViewById 只能找到第一個。<include> 導致 View 階層過深,影響渲染效能,配合 <merge> 扁平化。<include> 是 XML 佈局復用的基石,善用它能大幅減少重複代碼。配合 <merge>、ViewStub(按需延遲載入),能構建高效、可維護的 UI 架構。