編輯:關於 Android 程式設計
即使 Android 內建了豐富的常用控件,實務上仍常遇到需要重用較複雜佈局的情況。此時可以善用 <include/> 與 <merge/> 兩個標籤,把一段佈局嵌入到另一段佈局之中。
可重用佈局這項能力非常實用:你可以把「確定/取消」按鈕列、或「進度條 + 文字說明」這類組合抽成獨立檔案,各處重複引用,並對它們進行統一維護。相比撰寫自訂 View,這種做法門檻更低、也更直覺。
先決定哪一段畫面需要重用,然後建立一個新的 XML 檔案來定義它。以下定義一個 ActionBar 樣式的標題列,因為它會出現在每個 Activity 中:
<FrameLayout
android:background="@color/titlebar_bg"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android">
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/graphic_logo" />
</FrameLayout>
在希望插入重用佈局的位置加上 <include/> 即可:
<LinearLayout
android:background="@color/app_bg"
android:gravity="center_horizontal"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android">
<include layout="@layout/titlebar" />
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:text="@string/hello" />
</LinearLayout>
你也可以覆寫被引入佈局的參數,但只限於以 android:layout_* 開頭的屬性:
<include
android:id="@+id/news_title"
android:layout_height="match_parent"
android:layout_width="match_parent"
layout="@layout/title" />
需要注意的是,若想覆寫 <include> 的佈局屬性,必須同時覆寫 android:layout_height 與 android:layout_width,否則其他屬性不會生效。
<merge> 的作用是在嵌入佈局時消除多餘的 View 容器。
舉例來說,主佈局是一個垂直的 LinearLayout,裡面有兩個需要在多處重用的 View。這兩個 View 若獨立成檔案,就必須有一個根節點。如果選用 LinearLayout 當根節點,結果會變成「垂直 LinearLayout 裡又嵌一個垂直 LinearLayout」——這層嵌套並非必要,還會額外增加測量與配置成本,拖慢畫面效能。
為避免這種冗餘容器,改用 <merge> 作為根節點:
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/add" />
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/delete" />
</merge>
這樣一來,系統在引入時會自動略過 <merge> 標籤,直接把兩個 Button 掛到 <include/> 所指定的位置,佈局層級維持扁平,效能自然更好。
Android 自定義 Toast:換掉系統默認的樸素樣式
系統自帶的 Toast 樣式實在簡單,想加個圖標、改個背景色就得自己動手。本文示例演示如何通過 setView 把自定義佈局塞進 Toast。 效果預覽 代碼 //
OpenCV 實戰:用腐蝕運算實現圖像暗區擴張
效果預覽 原理與源碼 KqwOpenCVBlurDemo 暗區擴張,也就是腐蝕。要實現這種效果,只需選取一個合適大小的核,用核覆蓋範圍內的最小值替換錨點像素——暗像素
Android ProgressBar 自訂樣式:動畫幀切換實作
本文要介紹的是如何用動畫方式來自訂 ProgressBar 的樣式,整理出來供大家參考。這個做法其實是參考其他前輩的思路——透過逐幀動畫來呈現載入效果,這裡順手也把它記錄
Android Volley 源碼解析:從 RequestQueue 到網絡回調
Volley 工作流程概覽 Volley 是 Android 上常見的網路請求框架,適合處理小型、高頻次的請求。要理解它的運作方式,可以從 RequestQueue 的建