Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 版面配置技巧:用 include 標籤消除重複程式碼

編輯:關於 Android 程式設計

撰寫版面配置時,難免會遇到某些區塊在每個畫面都要重複出現,例如標題列或頁尾。最直白的做法当然是複製貼上,但這會讓後續維護變成噩夢——改一個地方要改十個檔案。

include 標籤就是為了解決這個問題,有 C/C++ 經驗的人一看就懂:把另一份版面配置檔合併進來即可。

上圖中上下兩個文字區塊,就是分別以 include 引入的。

activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="30dp"
        layout="@layout/header" />

    <ViewStub android:id="@+id/pic_stub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:inflatedId="@+id/pic_view_id_after_inflate"
        layout="@layout/pic_view" />

    <include layout="@layout/footer" />
</RelativeLayout>

中間那個 ViewStub 留待下一篇說明,這裡先看兩個 include 的差異。

第一個 include 寫法較完整,直接設定了寬高與對齊屬性,讓它被放在版面頂端。

第二個 include 什麼屬性都沒設,位置卻正確地落在頁面底部。

這兩種寫法之所以都能運作,是因為 include 的屬性有兩個下場:一是在 include 標籤本身指定,二是寫在該版面配置檔的根節點上。前者會覆蓋後者。

header.xml

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center_horizontal"
    android:text="Header Without Properties!" />

這裡刻意把寬高都設為 0,就是為了示範「完全交由 include 標籤來決定版面屬性」的用法。

footer.xml

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="30dp"
    android:gravity="center_horizontal"
    android:text="With Properties!" />

這個的根節點屬性寫得很完整,所以呼叫端直接引用即可。

使用 include 的幾個注意事項

● 若需要取得被引入版面中的子元件 id,可以用 android:id 為 include 標籤本身指定一個 id,再以 findViewById 取得整個區塊,往下繼續查找子 View。若不指定,findViewById 仍可直接搜尋到子元件,但區塊本身無法被整體操作(例如整塊隱藏)。

● 被引入的版面配置檔,其根節點只能有一個。若原本有多個並列的根節點,需先用 LinearLayout 或 RelativeLayout 包起來。

● layout_width 與 layout_height 若要透過 include 覆寫,必須同時在 include 標籤上明確指定這兩個屬性,否則覆寫不會生效。

● include 有助於消除重複,但也別過度切割。若某個區塊只在一處使用且沒有重用價值,獨立成檔反而增加跳轉成本。

作者:jason0539
部落格:
https://blog.csdn.net/jason0539

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved