編輯:關於 Android 程式設計
Android 提供了各種元件來實作小而可重複使用的互動元素,但當版面需要複用一整塊較大的元件時,該怎麼辦?為了有效率地重用完整版面,你可以使用 <include/> 與 <merge/> 這兩個標籤,把另一份版面嵌入目前的版面檔。
這個機制讓「自訂檢視」的價值被放大:把獨立的 UI 元件寫成一個版面檔,之後任何 Activity 都能直接嵌入,而不必複製貼上。
先建立一個新的 XML 檔定義要重用的部分。以下示範一個標題欄版面,可被插入到每個 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 也可以覆寫被引入版面的所有 layout_* 參數,例如重新指定 id 與尺寸:
<include
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/title" />
但這裡有個規則必須記住:若要用 include 覆寫版面屬性,就必須同時覆寫 android:layout_height 與 android:layout_width,否則其他屬性不會生效。
<merge/> 的作用是消除嵌入時產生的多餘 View Group。舉例來說,若你的可重用版面本身是一個垂直 LinearLayout,裡面有兩個子檢視,當它被嵌入另一個垂直 LinearLayout 時,結果就是「垂直 LinearLayout 裡包一個垂直 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 出現的位置。
include 負責「把 A 版面放進 B 版面」,merge 負責「去掉多餘的容器」。兩者常搭配使用:merge 當根節點、include 來引入。要留意 merge 不能單獨使用,它必須伴隨 include 才有意義,因為它本身不會產生任何檢視;此外 merge 也無法透過 include 覆寫自身的 layout 參數,因為那些參數會被套用到父容器上。適度使用這兩個標籤,能有效壓淺版面層級,對 ListView 這類需要大量重複繪製的畫面改善明顯。
Android 自訂 View 實作:在本機產生驗證碼
在 App 本機產生驗證碼,主要目的是避免使用者無腦連點「請求」按鈕。這個範例同時也是拿來練手自訂 View 的好題目,先看成果: 可自訂的項目包括: *干擾線數量*干
Android 網絡編程:獲取並解析網絡上的 XML
要在 App 中取得網絡上的 XML,同樣需要伺服器端配合。本文以「最新資訊列表」為例,走一遍伺服器產生 XML、客戶端抓取並解析的完整流程。 一、建立伺服器端 專案結構
Android ScrollView 的兩種宣告方式
Android 的版面配置一般來說有兩種宣告方式:一種寫在 XML 裡,另一種用程式碼動態建立。ScrollView 兩者都支援。 方式一:XML 宣告 <?xm
Android 懸浮 Dialog 實作:自訂位置、寬度與點擊外部關閉
懸浮 Dialog 常用於底部選單或浮動操作面板。透過 Dialog 搭配 WindowManager.LayoutParams,可以自訂顯示位置、寬度與高度。 Dial