ConstraintLayout(约束布局)是 Android Studio 推荐的布局方式,能够实现灵活的布局,减少控件之间的嵌套,从而优化界面的渲染性能。
官方文档:
以前我们用 LinearLayout、RelativeLayout 等实现的布局,现在用 ConstraintLayout 都可以实现,而且布局更轻巧,更扁平。
举个例子,要实现下面的布局,一个图标和一段文字两者居中对齐,而且文本长度不固定,考虑一下需要怎么做?

以前,我们可能会采用下面这种方式实现,通过嵌套一层 LinearLayout 来包裹要居中的元素,最后实现的效果没有任何问题,但不是最优的方案。

有了 ConstraintLayout 后,一切变得那么简单。不再需要嵌套一层,直接给元素添加约束就可以,二者通过 packed 合为一体,布局更加扁平。

这是 ConstraintLayout 的 ChainStype 属性,LinearLayout 的 layout-weight 属性也包含在其中,还可以指定左右边距的比例,实在是太灵活、太强大了。

除此之外,还有 GuideLine,Barrier,Group,PlaceHolder 等用法,支持相对定位、角度定位、比例尺寸约束等特性,有了 ConstraintLayout 还要啥自行车。
另外,从 Android Studio 的 Layout Editor 界面中可以看出,官方已经不推荐使用 Legacy 里的控件,包括 ListView、GridView、RelativeLayout 等。Layouts 里的 ConstraintLayout、LinearLayout 和 FrameLayout 可以实现绝大多数的布局,列表使用 RecyclerView 就够了。在控件选择上,没有最好的,只有最合适的。


如果想了解更多,推荐这篇文章:约束布局ConstraintLayout看这一篇就够了
网友评论