編輯:Android 開發實例
雖然 Android 提供了各式各樣的元件來拼湊小而可重複使用的互動元素,但當畫面需要整塊重複使用某個大型元件時,就需要更完整的佈局複用手段。透過 <include/> 與 <merge/> 這兩個標籤,你可以把一個佈局嵌入到另一個佈局之中,讓自訂的 UI 元件更容易被到處引用。
佈局複用的威力在於,你能把「是/否」按鈕面板、帶說明文字的自訂進度條這類複雜結構,抽離成獨立檔案集中管理,再插入到各個畫面裡,大幅降低重複維護的成本。
一旦確認某個佈局需要重複使用,就替它建立一個新的 XML 檔案。以下是一段來自 G-Kenya 專案、用來定義標題欄的佈局,它可以被插入到每個 Activity 中:
<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>
這裡的根視圖,其尺寸應該要與它將被插入的父佈局中對應位置相符。
在你想嵌入可複用佈局的地方,加入 <include/> 標籤。以下示範如何加入標題欄:
<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_* 屬性):
<include android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/title"/>
不過要留意:若你打算覆寫佈局屬性,就必須同時覆寫 android:layout_height 與 android:layout_width,否則其他屬性將無法生效。
<merge/> 標籤的用途,是排除「把一個佈局插入到另一個佈局時」所多產生的冗餘 View Group。舉例來說,假設你的可複用佈局是一個包含兩個子視圖的垂直 LinearLayout,當它被嵌入另一個同樣是垂直的 LinearLayout 時,結果就會變成「垂直 LinearLayout 裡又包了一層垂直 LinearLayout」。這種多餘的巢狀結構毫無意義,還會拖慢 UI 效能。
為了避免這類冗餘,你可以把 <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 所在的位置,省下一層無用的容器。
Java 開發環境建置(三):JDK、JRE 與 JVM 的關係
寫 Java 一定會遇到三個縮寫:JDK、JRE、JVM。搞不清楚它們的關係,後續碰到版本與環境問題就會一頭霧水。這一篇順便把環境變數的作用也講清楚。 什麼是環境變數
Android JetPlayer 教學:用 JetCreator 製作互動式音樂內容
Android 平台內建了 JET 引擎,讓應用程式能播放具互動性的 JET 音訊內容——這是一種把音樂拆成多個片段(segment)、可依遊戲狀態即時排列播放的格式,特
Android 登入介面實作教學
登入畫面幾乎是每一款需要帳號的應用必備的環節,它透過詢問使用者的帳號與密碼來完成身分驗證,無論是登入 Facebook、微博還是自家服務都離不開它。 本章將說明如何打造一
Android Fragment 多級跳轉與逐級返回的完整實現方案
Fragment 的返回鍵管理是個經典難題:頁面一層層往下跳,按返回要一級級退回去,中間某一層可能還想攔截返回事件做別的事(比如先關菜單而不是退出)。本文給出一套接口 +