編輯:關於 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 的版面配置,其根節點的 layout_width 與 layout_height 必須先定義,否則會被忽略;而 include 標籤上若另外指定了這兩個屬性,則以 include 上的設定為準。這個優先順序常讓人踩坑,值得記住。
另外,<include /> 無法替被引入區塊內部的子檢視改 id。如果同一頁需要用到兩個相同模組、又要分別操作,就得靠 android:id 在 include 上重新指定根節點的 id,再從那個節點往下找子檢視。
Android 多媒體:人臉識別(FaceDetector)
1. 相關背景 Google 於 2006 年收購 Neven Vision 公司(該公司擁有十多項應用於行動裝置的圖像識別專利),藉此獲得圖像識別技術,並很快應用於 P
Android Studio 安裝與配置完整圖文攻略
為何值得投入 Android Studio 作為 Google 官方主推的新一代 Android 開發環境,Android Studio 幾乎已成為開發者的標配。相比舊有
Android 自定義 ImageView 實作手勢縮放瀏覽器完整解析
在 Android 裡想讓圖片支援雙指縮放、單指拖動、雙擊放大這些常見手勢,最直接的做法就是自己寫一個 View。本文以 TouchImageView 為例,它繼承自 I
Android 螢幕旋轉適配全解析
預設旋轉行為 當 Android 螢幕旋轉時,重力感應會觸發 Configuration 變更。預設情況下,系統會銷毀目前的 Activity,再依新的方向重新建立。因此