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

用 include 標籤重用版面配置:讓 UI 維護成本降下來

編輯:關於 Android 程式設計

重複寫同樣的配置,遲早出問題

如果每個 XML 檔都把相同的區塊重寫一遍,會有兩個後果:一是程式碼冗餘、可讀性差;二是修改時到處都得改,對後期維護非常不利。

所以合理的做法是把共用區塊獨立成一個模組,需要時用 <include /> 標籤引入。

最典型的例子:標題欄

很多應用的每個頁面頂端都有一條標題欄。

圖 標題欄示例

如果專案裡大部分 Activity 都需要這條標題欄,就把它獨立成一個 XML 檔:

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:background="@drawable/navigator_bar_bg"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:id="@android:id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:hint="title"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@android:id/closeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@drawable/close" />
</RelativeLayout>

把這個檔案命名為 navigator_bar.xml,其他需要標題欄的 Activity 只要一行就能引入:

<include layout="@layout/navigator_bar" />

心得

專案初期通常就能大致確定整體 UI 風格,所以早期就該做點規劃,把通用模組先抽出來。等到畫面數量堆到二三十個才回頭整理,成本會高上許多。

值得優先抽出的共用區塊大致有這幾類:

1)背景。有些應用在各頁面會用統一背景,而預設背景後續經常被調整,獨立成模組能省下大量重複修改。

2)頂部標題欄。若應用有統一的標題欄,第一時間就該抽出。

3)底部導覽欄。若大部分 Activity 的底部導覽相同,同樣值得模組化。

4)ListView。幾乎所有應用都會用 ListView 展示多筆資料,而它的樣式後期經常需要調整,獨立成通用模組比較好維護。

include 的實務細節

被 include 的版面配置,其根節點的 layout_width 與 layout_height 必須先定義,否則會被忽略;而 include 標籤上若另外指定了這兩個屬性,則以 include 上的設定為準。這個優先順序常讓人踩坑,值得記住。

另外,<include /> 無法替被引入區塊內部的子檢視改 id。如果同一頁需要用到兩個相同模組、又要分別操作,就得靠 android:id 在 include 上重新指定根節點的 id,再從那個節點往下找子檢視。

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