1. 程式人生 > >Android merge標籤講解與例項

Android merge標籤講解與例項

單獨將<merge />標籤做個介紹,是因為它在優化UI結構時起到很重要的作用。目的是通過刪減多餘或者額外的層級,從而優化整個Android Layout的結構。核心功能就是減少冗餘的層次從而達到優化UI的目的!

將通過一個例子來了解這個標籤實際所產生的作用,這樣可以更直觀的瞭解<merge/>的用法。

建立一個簡單的Layout,其中包含兩個Views元素:ImageViewTextView 預設狀態下我們將這兩個元素放在FrameLayout中。其效果是在主檢視中全屏顯示一張圖片,之後將標題顯示在圖片上,並位於檢視的下方。以下是xml程式碼:

<?xml

 version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent">

 <ImageView

 android:layout_width="fill_parent"

 android:layout_height="fill_parent"

 android:scaleType="center"

 android:src="@drawable/rain" />

 <TextView

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_marginBottom="20dip"

 android:layout_gravity="center_horizontal|bottom"

 android:padding="12dip"

 android:background="#AA000000"

 android:textColor="#ffffffff"

 android:text="Golden Gate2" />

</FrameLayout>

應用上邊的Layout執行的檢視為

【Android】Merge講解與例項

啟動 tools> hierarchyviewer.bat工具檢視當前UI結構檢視

【Android】Merge講解與例項

我們可以很明顯的看到出現了兩個framelayout節點,很明顯這兩個完全意義相同的節點造成了資源浪費(這裡可以提醒大家在開發工程中可以習慣性的通過hierarchyViewer檢視當前UI資源的分配情況),那麼如何才能解決這種問題呢(就當前例子是如何去掉多餘的frameLayout節點)?這時候就要用到<merge />標籤來處理類似的問題了。我們將上邊xml程式碼中的framLayout替換成merge

<?xml version="1.0" encoding="utf-8"?>

<merge xmlns:android="http://schemas.android.com/apk/res/android">

 <ImageView

 android:layout_width="fill_parent"

 android:layout_height="fill_parent"

 android:scaleType="center"

 android:src="@drawable/rain" />

 <TextView

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_marginBottom="20dip"

 android:layout_gravity="center_horizontal|bottom"

 android:padding="12dip"

 android:background="#AA000000"

 android:textColor="#ffffffff"

 android:text="Golden Gate2" />

</merge>

UI結構圖:

【Android】Merge講解與例項

執行程式後在Emulator中顯示的效果是一樣的,可是通過hierarchyviewer檢視的UI結構是有變化的,當初多餘的FrameLayout節點被合併在一起了,或者可以理解為將merge標籤中的子集直接加到ActivityFrameLayout跟節點下(這裡需要提醒大家注意:所有的Activity檢視的根節點都是frameLayout)。如果你所建立的Layout並不是用framLayout作為根節點(而是應用LinerLayout等定義root標籤),就不能應用上邊的例子通過merge來優化UI結構。

除了上邊的例子外,meger還有另外一個用法,當應用Include或者ViewStub標籤從外部匯入xml結構時,可以將被匯入的xmlmerge作為根節點表示,這樣當被嵌入父級結構中後可以很好的將它所包含的子集融合到父級結構中,而不會出現冗餘的節點。

另外有兩點需要特別注意

<merge />只可以作為xml layout的根節點。

當需要擴充的xml layout本身是由merge作為根節點的話,需要將被匯入的xml layout置於viewGroup中,同時需要設定attachToRootTrue