萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 打造可復用 UI 組件: 標籤完整指南與實戰技巧

為什麼需要可復用 UI 組件?

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:直屏專用內容

如此一來,主框架只維護一份,內容隨裝置方向自動切換。

常見錯誤與避坑指南

  1. 忘記成對覆蓋寬高:只設 layout_width 不設 layout_height 會導致屬性失效,繼承原佈局值。
  2. ID 衝突:同一佈局多次 <include> 同一資源時,必須指定不同 android:id,否則 findViewById 只能找到第一個。
  3. 巢狀過深:濫用 <include> 導致 View 階層過深,影響渲染效能,配合 <merge> 扁平化。

總結

<include> 是 XML 佈局復用的基石,善用它能大幅減少重複代碼。配合 <merge>、ViewStub(按需延遲載入),能構建高效、可維護的 UI 架構。

copyright © 萬盛學電腦網 all rights reserved