編輯:關於 Android 程式設計
Android 內建了大量可重複使用的小型互動元件,但真實專案裡往往更需要復用「較大的片段」——整塊佈局檔。要有效率地做到這件事,關鍵是 <include /> 與 <merge /> 這兩個標籤。
把佈局抽出來獨立管理,能帶來兩個好處:一是像「Yes / No 兩個按鈕的確認面板」或「帶文字說明的進度條」這種元件,可以隨處重複使用;二是讓複雜畫面中的每個區塊各自獨立,需要時再組裝起來。搭配自訂 View 時,這種做法尤其省事。
先想清楚這個元件長什麼樣子,然後建立對應的 xml。以下是一個自訂標題欄 titlebar.xml:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/titlebar_bg">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
</FrameLayout>
由於這份佈局會被嵌進其他佈局中,它的根檢視(root View)最好能精確對應實際使用情境。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar" />
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
...
</LinearLayout>
如果同一個元件在不同場合需要不同的尺寸或權重,可以在 <include /> 節點上直接覆寫被引入佈局的根檢視屬性——凡是 android:layout_ 開頭的屬性都可以覆寫。不過要注意:覆寫生效的前提是被引入佈局的根檢視本身有明確的 layout 寬高設定。
當被復用的佈局需要「兩個以上的子檢視」時,它必須有一個根檢視,否則編譯器會報錯。但如果你為了合規硬加一層 LinearLayout,就會變成「垂直 LinearLayout 裡再嵌一個垂直 LinearLayout」——多這一層毫無功能價值,只會拖慢 UI 效能。
原本的寫法:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="horizontal">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete" />
</LinearLayout>
改用 <merge /> 作為根節點:
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete" />
</merge>
如此一來,當你用 <include /> 引入這份佈局時,系統會忽略 merge 節點,直接把兩個 Button 放進父容器中替代 include 的位置。
判斷很簡單:被復用的片段只有單一根檢視(像一個 FrameLayout 包一張圖),用 include 即可;片段由多個並列子檢視組成、且不希望多一層容器,就用 merge。兩者常搭配使用,也是 View 繪製優化裡最不需要改動邏輯、就能削減檢視樹深度的一招。搭配 Layout 或 Hierarchy Viewer 觀察層級變化,效果會很直觀。
Android 線程優先級怎麼設?一次搞懂 Process.setThreadPriority
多線程寫得多了,你一定遇過這種尷尬:明明邏輯沒錯,畫面卻總是卡一下。問題往往不在演算法,而在 CPU 時間的分配。 Android 上的並發場景比桌面端更敏感。設備的算
Android 動畫實戰:從螢幕底部滑出的 PopupWindow
本文示範一個常見的互動效果:點擊後,面板從螢幕底部滑出。拍照/選圖、分享選單等情境幾乎都會用到這種設計。 以下仿作一個同類效果: 一、面板版面 take_pho
Android PopupWindow 使用範例
PopupWindow 基本用法 PopupWindow 可在畫面上彈出一個浮動視窗,常用於提示、選單或短暫操作。 建立與顯示 先建立要顯示的 root view,再
Android記憶體快取算法解析:從LRU、LFU到ImageLoader實作
前言 在Android圖片加載與資料快取場景中,記憶體快取扮演關鍵角色。適當的快取能減少重複加載,提高使用者體驗;但若策略不當,也可能造成記憶體壓力。本文以常見快取演算法