Android

Android Studio下HierarchyViewer的使

2016-11-03  本文已影响1895人  Rave_Tian

什么是HierarchyViewer

Hierarchy Viewer是随AndroidSDK发布的工具,位置在tools文件夹下,名为hierarchyviewer.bat。它是Android自带的非常有用而且使用简单的工具,可以帮助我们更好地检视和设计用户界面(UI),绝对是UI检视的利器,下面来详细介绍如何在Android Studio开发环境下使用Hierarchy Viewer。

如何在Android Studio开发环境下使用HierarchyViewer

1.启动模拟器,通过模拟器运行你的应用
※HierarchyViewer是无法连接真机进行调试

HierarchyViewer的官方介绍
文中提及To preserve security, Hierarchy Viewer can only connect to devices running a developer version of the Android system.即出于安全考虑,Hierarchy Viewer只能连接Android开发版手机或是模拟器(准确地说,只有ro.secure参数等于0且ro.debuggable等于1的android系统)。Hierarchy Viewer在连接手机时,手机上必须启动一个叫View Server的客户端与其进行socket通信。而在商业手机上,是无法开启View Server的,所以Hierarchy Viewer是无法连接到普通的商业手机。
可通过如下命令检验一台手机是否开启了View Server:
adb shell service call window 3
若返回值是:Result: Parcel(00000000 00000000 '........')" 说明View Server处于关闭状态
若返回值是:Result: Parcel(00000000 00000001 '........')" 说明View Server处于开启状态

若是一台可以打开View Server的手机(Android开发版手机 、模拟器or 按照本帖步骤给系统打补丁的手机),我们可以使用以下命令打开View Server:
adb shell service call window 1 i32 4939
使用以下命令关闭View Server:
adb shell service call window 2 i32 4939

模拟器运行的APP

2.打开Android Device Monitor(两种打开方式)
第一种:通过tool打开

通过tool打开
第二种:通过快捷图标打开 通过快捷图标打开

3.进入Android Device Monitor界面,打开HierarchyViewer

打开HierarchyViewer

4.加载出当前Activity的节点,可选中进行分析

HierarchyViewer视图

例子##

我们写一个简单的例子来演示一下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   android:id="@+id/relativelayout" 
   android:layout_width="match_parent" 
   android:layout_height="match_parent"> 
   <LinearLayout
        android:id="@+id/linearlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
        <Button
            android:id="@+id/button"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button!" />
    </LinearLayout>
</RelativeLayout>

代码就是加载出上面的layout界面,可以看见代码中故意多嵌套了一层LinearLayout。这也是模拟我们开发过程中不必要的布局嵌套。让我们来看看HierarchyViewer是怎么给我们展示的。

Example

我们可以很直观的看见RelativeLayout上面,直接放置了一个LinearLayout。像这种情况就是我们需要做优化的地方,我们完全可以将LinearLayout的子控件直接放在RelativeLayout内部,就减少了一层布局。我们的优化目标是尽量使得布局扁平化,减少布局深度。

上一篇 下一篇

猜你喜欢

热点阅读