Android性能優化——標籤

昨天小米5發佈(cpu 高通驍龍820,RAM 4GB)現在的工業水平來看 內存跟性能足夠高了。。。

作爲開發者來講 我們做的應用 要極致,要優雅。

Merge 標籤用於減少View樹的層次來優化Android的佈局。
下面來做個簡單的示例 查看界面的層級驗證一下 Merge 標籤 的效果。

示例:


主頁面:activity_main.xml (包含了 layout_merge.xml 佈局)

<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

  <ImageView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:src="@drawable/ic_launcher" />

  <include layout="@layout/layout_merge" />
</LinearLayout>

佈局頁面:layout_merge.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="這是 lyaout_merge " />
</RelativeLayout>

按着上面的代碼創建工程,運行後使用“DDMS -> Dump View Hierarchy for UI Automator”工具,界面層級如下:
這裏寫圖片描述

可以看出最下面的兩層 RelativeLayout 和 TextView是layout_merge.xml的內容。下面使用merge標籤可以查看下區別。
佈局文件 layout_merge.xml 修改如下:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="這是 lyaout_merge " />
</merge>

使用“DDMS -> Dump View Hierarchy for UI Automator”工具,界面層級如下:
merge使用後:
這裏寫圖片描述

與之前的相比少了一層RelativeLayout而實現的效果相同。
使用 include 包含佈局時,會自動忽略掉merge這一層,如上:TextView會與include同級, layout_merge.xml 內的 TextView會直接成爲 activity_main.xml的子view, TextView會直接繼承 LinearLayout 的屬性。
同理如果 activity_main.xml的父佈局 換成RelativeLayout 或者Framelayout,TextView會繼承RelativeLayout 或者Framelayout 位置也相應被改變。
如:activity_main.xml改成RelativeLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

  <ImageView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:src="@drawable/ic_launcher" />

  <include layout="@layout/layout_merge" />
</RelativeLayout>

那麼TextView的位置也就變了
這裏寫圖片描述


使用場景:

  • 子視圖不需要指定任何針對父視圖的佈局屬性,如上例子TextView僅僅需要直接添加到父視圖上用於顯示就行。
  • 另外一種是假如需要在LinearLayout裏面嵌入一個佈局(或者視圖),而恰恰這個佈局(或者視圖)的根節點也是LinearLayout,這樣就多了一層沒有用的嵌套,無疑這樣只會拖慢程序速度。而這個時候如果我們使用merge根標籤就可以避免那樣的問題,官方文檔 Android Layout Tricks #3: Optimize by merging 中的例子演示的就是這種情況。

注意點:

merge只能作爲XML佈局的根標籤使用。當Inflate以merge開頭的佈局文件時,必須指定一個父ViewGroup,並且必須設定attachToRoot爲true。

參考:

佈局優化
Android開發藝術探索 第十五章 第一節

發佈了38 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章