Android中ContraintLayout的优势和劣势

119 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

优势: 更加强大

  1. ContraintLayout缩减了视图层级.
  2. ContraintLayout比其它视图更加强大而且擅长动画, 比如它的子类MotionLayout.

劣势: 性能问题

  1. ConstraintLayout初始化比较耗时.
  2. ContraintLayout存在双重课税问题.

简化的显示系统包括3部分: Display & CPU & GPU

对于一个View而言, 它的渲染过程是Measure + Layout + Draw.

布局测量和双重课税

通常情况下, 框架会在绘制时执行阶段一次通过.

而执行布局和测量超过一次, 叫做双重课税.

就像RelativeLayout, 它的双重课税是:

  • 在第一次布局和测量的过程中, 框架按照子视图的要求计算了子视图的位置和尺寸.

  • 之后, 框架使用了来自第一次绘制的数据并且考虑进权重, 以图找到它的子视图的常规位置.

  • 再之后, 在第二次布局和测量的过程中, 框架最终决定了子视图的位置.

而对于其它的布局, 

  • LinearLayout如果设置了horizontal或者verticalmeasureWithLargestChild, 也会导致双重课税.

  • GridLayout有相似的问题. 尽管这个容器也允许相对位置, 但它正常情况下会通过预处理子视图之间的位置相对关系来避免双重课税. 然而, 如果布局使用了权重或者Gravity类, 这个预处理的好处便会丢失, 而且, 如果容器是个RelativeLayout的话, 框架可能得执行多次绘制过程.

  • 至于ConstraintLayout, 它有RelativeLayoutLinearLayout的双重能力. 既能设置子视图的相对位置(就像RelativeLayout一样), 也能为动态UI设置权重(这只有在LinearLayout中是可能的).

最后, 简要介绍一下ContraintLayout的基本使用.

ContraintLayout的子View有四个方向的约束条件

app:layout_constraintBottom_toBottomOf
app:layout_constraintEnd_toEndOf
app:layout_constraintStart_toStartOf
app:layout_constraintTop_toTopOf

上面的约束条件是将View约束在目标View之内,那么其实可以推理出在之外的情形

app:layout_constraintBottom_toTopOf
app:layout_constraintEnd_toStartOf
app:layout_constraintStart_toEndOf
app:layout_constraintTop_toBottomOf

其Value指定为parent或者某个兄弟View的id即可.

想要查看ContraintLayout的更加详细的用法, 可以查看这篇文章