小白:之前分享了ViewStub標簽的使用。Android還有其它優化布局的方式嗎?
小黑:<merge />標簽用於降低View樹的層次來優化Android的布局。先來用個樣例演示一下:
首先主須要一個配置文件activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="merge標簽使用" /> </RelativeLayout>
再來一個最簡單的Activity,文件名稱MainActivity.java
package com.example.merge; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
小白:按着上面的代碼創建project,執行后使用“DDMS -> Dump View Hierarchy for UI Automator”工具,截圖例如以下
merge 使用前

布局文件activity_main.xml改動內容例如以下:
<merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="merge標簽使用" /> </merge>
小白:使用“DDMS -> Dump View Hierarchy for UI Automator”工具。截圖例如以下
merge使用后

某些時候,自己定義可重用的布局包括了過多的層級標簽,比方我們
比如:這種話。使用<include>包括上面的布局的時候。系統會自己主動忽略merge層級。而把兩個button直接放置與include平級
小白:什么情況考慮使用Merge標簽?
小黑:一種是向上面的樣例一樣。子視圖不須要指定不論什么針對父視圖的布局屬性,樣例中TextView只須要直接加入到父視圖上用於顯示即可。
第二種是假如須要在LinearLayout里面嵌入一個布局(或者視圖),而恰恰這個布局(或者視圖)的根節點也是LinearLayout,這樣就多了一層沒實用的嵌套,無疑這樣僅僅會拖慢程序速度。而這個時候假設我們使用merge根標簽就能夠避免那樣的問題,官方文檔Android Layout Tricks #3: Optimize by merging 中的樣例演示的就是這樣的情況。
小白: <merge />標簽有什么限制沒?
小黑: <merge />僅僅能作為XML布局的根標簽使用。
當Inflate以<merge />開頭的布局文件時。必須指定一個父ViewGroup,而且必須設定attachToRoot為true。
小黑:merge標簽另一些屬性可供使用。詳細能夠查看API文檔,比如
android:layout_width、
android:layout_height等
參考資料:
《Android應用性能優化》 第8章 圖形