將經過一個例子來了解這個標籤實際所產生的做用,這樣能夠更直觀的瞭解<merge/>的用法。java
創建一個簡單的Layout,其中包含兩個Views元素:ImageView和TextView 默認狀態下咱們將這兩個元素放在FrameLayout中。其效果是在主視圖中全屏顯示一張圖片,以後將標題顯示在圖片上,並位於視圖的下方。如下是xml代碼:android
<?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運行的視圖爲:工具
啓動 tools> hierarchyviewer.bat工具查看當前UI結構視圖:優化
咱們能夠很明顯的看到出現了兩個framelayout節點,很明顯這兩個徹底意義相同的節點形成了資源浪費,那麼如何才能解決這種問題呢(就當前例子是如何去掉多餘的frameLayout節點)?這時候就要用到<merge />標籤來處理相似的問題了。spa
這裏能夠提醒你們在開發工程中能夠習慣性的經過hierarchyViewer查看當前UI資源的分配狀況。 Hierarchy Viewer是隨AndroidSDK發佈的工具,位置在tools文件夾下,名爲hierarchyviewer.bat。它是Android自帶的很是有用並且使用簡單的工具,能夠幫助咱們更好地檢視和設計用戶界面(UI),絕對是UI檢視的利器。具體能夠看這篇文章 Android工具Hierarchy Viewer.net
咱們將上邊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結構圖:code
運行程序後在Emulator中顯示的效果是同樣的,但是經過hierarchyviewer查看的UI結構是有變化的,當初多餘的FrameLayout節點被合併在一塊兒了,或者能夠理解爲將merge標籤中的子集直接加到Activity的FrameLayout跟節點下(這裏須要提醒你們注意:全部的Activity視圖的根節點都是frameLayout)。若是你所建立的Layout並非用framLayout做爲根節點(而是應用LinerLayout等定義root標籤),就不能應用上邊的例子經過merge來優化UI結構。xml
除了上邊的例子外,meger還有另一個用法,當應用Include或者ViewStub標籤從外部導入xml結構時,能夠將被導入的xml用merge做爲根節點表示,這樣當被嵌入父級結構中後能夠很好的將它所包含的子集融合到父級結構中,而不會出現冗餘的節點。blog
另外有兩點須要特別注意:
1.<merge />只能夠做爲xml layout的根節點。
2.當須要擴充的xml layout自己是由merge做爲根節點的話,須要將被導入的xml layout置於 viewGroup中,同時須要設置attachToRoot爲True。