1. 程式人生 > >Android 性能優化 四 布局優化merge標簽的使用

Android 性能優化 四 布局優化merge標簽的使用

auto rac ack textview views public package extends src



小白:之前分享了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 使用前
技術分享

小黑:最以下兩層RelativeLayout與TextView就是activity_main.xml布局中的內容,上面的FrameLayout是Activity setContentView加入的頂層視圖。以下使用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使用後
技術分享


小黑:FrameLayout以下直接就是TextView,與之前的相比少了一層RelativeLayout而實現的效果同樣。






某些時候,自己定義可重用的布局包括了過多的層級標簽,比方我們
比如:這種話。使用<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等

參考資料: Re-using Layouts with <include/> Android Layout Tricks #2: Reusing layouts include與merge標簽結合使用樣例
Android Layout Tricks #3: Optimize by merging 《Android應用性能優化》 第8章 圖形 性能優化之布局優化 Merge源代碼


很多其它優化相關的文章詳見:《Android 基礎學習文章匯總》 第三部分 性能優化



Android 性能優化 四 布局優化merge標簽的使用