项目github地址:https://github.com/CameloeAnthony/CascadeLayout
1 在开发中,不合理的布局会使我们的应用程序UI性能变慢,HierarchyViewer能够可视化的角度直观地获得UI布局设计结构和各种属性的信息,帮助我们优化布局设计。HierarchyViewer是我们优化程序的工具之一,它是Android自带的非常有用的工具,可以帮助我们更好地检视和设计用户界面(UI),绝对是UI检视的利器。
Android UI 优化——使用HierarchyViewer工具
Hierarchy Viewer官方文档
2来看看我们这个自己的项目,打开项目之后运行Hierarchy viewer
我们得到如下的效果:
3 我们再来看看自己的布局代码
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cascade="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent">
<com.nsu.edu.cascadelayout.CascadeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
cascade:horizontal_spacing="30dp"
cascade:vertical_spacing="20dp">
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#ff0000" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#00ff00" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#0000ff" />
</com.nsu.edu.cascadelayout.CascadeLayout>
</FrameLayout>
很明显我们自己写的外部的这个FrameLayout和应用自带的id为content 的FrameLayout造成了视图的FrameLayout重叠。
4 于是我们可以采用使用Merge 标签来减少视图层级结构。目的是通过删减多余或者额外的层级,从而优化整个Android Layout的结构。
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cascade="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent">
<com.nsu.edu.cascadelayout.CascadeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
cascade:horizontal_spacing="30dp"
cascade:vertical_spacing="20dp">
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#ff0000" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#00ff00" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#0000ff" />
</com.nsu.edu.cascadelayout.CascadeLayout>
</merge>
5 我们再来看看Hierarchy Viewer的效果
6 当初多余的FrameLayout节点被合并在一起了,或者可以理解为将merge标签中的子集直接加到Activity的FrameLayout跟节点下(这里需要提醒大家注意:所有的Activity视图的根节点都是frameLayout)。如果你所创建的Layout并不是用framLayout作为根节点(而是应用LinerLayout等定义root标签),就不能应用上边的例子通过merge来优化UI结构。