我們可以使用HierarchyViewer來進行布局的復雜程度以及冗余的分析
注意:如果使用真機調試,如果真機沒有獲得root權限,是不能使用HierarchyViewer進行分析的.會在dos窗口有[Unable to get view server version from device 的報錯,解決辦法網上有一些,但并不好用,所以建議大家用模擬器分析
HierarchyViewer的位置在sdk目錄下的tools文件夾中
接下來我們一步一步介紹大家使用這個工具
1 定義一個頁面的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.dgtech.myapplication.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="@+id/bt"
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
然后運行該頁面所屬的app,然后打開HierarchyViewer
雙擊選擇我們的應用程序,接下來是這樣的展示
我們點擊任何一個布局(比如截圖中選中的那個),在右下角都會顯示該布局在屏幕中的顯示情況
我們發(fā)現,我們在布局中定義的是一個LinearLayout,里面有一個TextView,一個Button,但是這里卻顯示了這么多個布局,我們沒有寫啊,這哪來的?
答案是:這些都是Android系統給我們加上的
比如我們LinearLayout的父布局是ContentFrameLayout,它的id是content是不是有些熟悉?我們在Activity里面設置布局的時候不正是setContentView()嘛,這個就是這個方法名字的由來,應為和ContentFrameLayout平級的還有一個ActionBarContainer
圖示說明:
具體哪個布局對應屏幕的哪一塊,大家可以自己去試試,很有意思.
我們接著分析UI性能
我們單擊選中我們的LinearLayout布局,再點擊PoofileNode按鈕,如下圖
會顯示這個布局measure的時間,layout的時間,draw的時間
三個帶顏色的按鈕依次表示measure,layout,draw
綠色表示用時短
黃色表示用時稍長
紅色表示用時過長
這個時候我們就需要針對有紅色部分優(yōu)化了
這個工具很實用,大家需要自己摸索嘗試了