編輯:關於 Android 程式設計
Android 官方在佈局優化中提到三個常用標籤:include、merge 與 ViewStub。它們分別負責重用佈局、減少多餘層級,以及延後載入不常用元件。以下說明各自的使用方式與適用情境。
include 可把另一個 XML 佈局嵌入目前畫面,適合處理重複的標題列、列表項或頁尾。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/layout_title" />
</LinearLayout>
使用 include 時,layout_width 與 layout_height 是必要的;若 include 指定 id,會覆蓋被引入佈局根節點原本的 id。宣告多個相同 include 時,可利用不同 id 再分別 findViewById。
merge 的作用是把子節點直接合併到父容器,而不額外建立一層 ViewGroup。它常用來取代 FrameLayout,或在 include 時避免重複包一層 LinearLayout。
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="新增" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="刪除" />
</merge>
當系統加入這個 merge 佈局時,會忽略 merge 節點本身,直接把兩個 Button 放進父容器,从而降低檢視層級。
ViewStub 是一個不可見且不佔用空間的佔位元件。適合放在不常用但可能需要顯示的區塊,例如錯誤提示、載入中遮罩或進度條。
<ViewStub
android:id="@+id/stub_import"
android:inflatedId="@+id/panel_stub"
android:layout="@layout/progress_overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
真正需要顯示時,可以設定可見性或直接 inflate:
ViewStub stub = findViewById(R.id.stub_import);
stub.setVisibility(View.VISIBLE);
View panel = stub.inflate();
使用 ViewStub 的重點是延後載入,避免初始化時就解析所有不常用佈局。它能有效降低初始渲染成本,但要注意它與 merge 的搭配會受到平台版本與使用情境影響,實作前應先驗證。
Android 自定義控件屬性與刮刮樂:打碼、保存圖片完整實作
這個 Demo 整合自定義 View、自定義屬性與圖形處理,可作為刮刮樂、圖片打碼與圖片保存的綜合練習。 自定義屬性 在 res/values 建立 declare-s
Android 三方支付整合:支付寶、微信、銀聯的後台下單 API 設計
做支付功能時,最容易被忽略的其實是「客戶端向後台要參數」這一段。本文把這層介面的設計整理出來,涵蓋請求格式、回應結構,以及三家通路各自需要的參數樣貌。 請求參數樣例:
使用 Builder 模式自訂 Android Dialog
在實際專案中,系統 Dialog 未必能符合產品設計風格。因此,自訂 Dialog 是常見需求。若希望呼叫方式簡潔、可讀性高,Builder 模式是一個很合適的選擇。 為
Cordova InAppBrowser 插件改造:讓 WebView 的 input type=file 支援選擇文件
改造後支援的能力 1. 幾乎支援所有 Android 版本,從 2.x 到 7.0 Android 4.4、4.4.1 與 4.4.2 無法支援,因為當時 Google