标签的使用

Android UI 开发中常用的标签和控件includemergeViewStub,最终目的便是为了避免过深的布局层级

Deep layouts - Layouts with too much nesting are bad for performance. The default maximum depth is 10.


include标签是为了解决重复定义相同布局的问题,在产品设计中常出现应用多个界面中一个模块需要呈现相同的布局样式,对我来说,这就是一个可重用的布局组件,可以将其使用单独的layout抽离,通过include标签将其添加到对应的布局中。

The tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. For example, if your main layout is a vertical LinearLayout in which two consecutive views can be re-used in multiple layouts, then the re-usable layout in which you place the two views requires its own root view. However, using another LinearLayout as the root for the re-usable layout would result in a vertical LinearLayout inside a vertical LinearLayout. The nested LinearLayout serves no real purpose other than to slow down your UI performance.

标签可减少include引入重用布局时的层级冗余问题。
比如一个垂直的线性布局,并且复用的布局也是一个类似的垂直线性布局。那么,使用引入重用布局时会出现一个 LinearLayout 作为另一个 LinearLayout 的根节点,这相当于真个Layout的层级结构多了一层且没有任何意义。此时可以使用标签来替代可重用 Layout的根节点。

ViewStub

ViewStub的官方描述是:
ViewStub is a lightweight view with no dimension and doesn’t draw anything or participate in the layout. As such, it's cheap to inflate and cheap to leave in a view hierarchy. Each ViewStub simply needs to include the android:layout attribute to specify the layout to inflate.
ViewStub是一个不可视且大小为0的视图,可以延迟到运行时填充布局资源。当ViewStub设置为visible或调用inflate()之后,就会填充布局资源,ViewStub便会被填充的视图替代。

总结下来它具有以下几个特性:

  • 需主动设置visible或调用inflate()才会填充到父布局,要被加载的子布局通过android:layout属性来设置。
  • 未主动设置时其默认不可见,不会绘制且不占用布局(此时的不可见与常用的View.setVisibility(View.GONE)有本质区别,它不会显示在当前布局的整个层级结构中)
  • 显示后ViewStub元素不再是View视图的一部分。它被引用的资源替换掉,根布局的ID即为ViewStub属性中android:inflatedId指定的ID。
  • ViewStub只能Inflate一次,之后ViewStub对象会被置为空。按句话说,某个被ViewStub指定的布局被Inflate后,就不能够再通过ViewStub来控制它了。所以它不适用于需要按需显示隐藏的情况。
  • ViewStub只能用来Inflate一个布局文件,而不是某个具体的View,当然也可以把View写在某个布局文件中。如果想操作一个具体的view,还是使用visibility属性。
  • VIewStub中不能嵌套merge标签。

结语

以上代码实现十分基础,之所以做这个总结是因为它们是我在实际开发中经常使用的,然后通过自己的理解和[Hierarchy Viewer]层级图更直观的解释为什么需要这么使用它们。

参考

  • ViewStub源码解析
  • android.view.ViewStub
  • Optimizing Layout Hierarchies
  • Loading Views On Demand

你可能感兴趣的:(标签的使用)