ConstraintLayout

ConstraintLayout(约束布局)的出现是为了在Android应用布局中保持扁平的层次结构,减少布局的嵌套,为应用创建响应快速而灵敏的界面。ConstraintLayout可以替代其他布局。

由来

Android Studio在3.5.+版本之后创建布局时,默认的布局根节点就是ConstraintLayout,虽然可以通过修改Android Studio的默认配置以及自己手动选择根节点来继续使用LinearLayoutRelativeLayoutGrideLayoutTabLayoutFrameLayout等布局,但是这些布局毕竟相对于ConstraintLayout来说局限性很大,所以这里对常用的ConstraintLayout中的一些属性进行说明。

ConstraintLayout的属性

ConstraintLayout包含很多特性,这里针对一些常用的特效进行说明。通过实现以上布局的效果来进行说明。

实现类似LinearLayout的效果

可以使用ConstraintLayout来实现,LinearLayout从左到右,从上到下的布局效果。

LinearLayout从左到右

ConstraintLayout具有RelativeLayout的能力,即具有相对性(Relative position),可以将一个控件置于相对于另一个控件的位置。这里使用相对性实现该效果:
ConstraintLayout简单体验

LinearLayout从上到下

ConstraintLayout具有链表性(Chains),链使我们能够对一组在水平或竖直方向互相关联的控件的属性进行统一管理。

一组控件它们通过一个双向的约束关系链接起来,并且链的属性由一条链的头结点控制。实现该效果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Uoulz7SY-1594656939873)(./constraint/linear_vertical.png)]

Chain style

layout_constraintHorizontal_chainStyle:水平链条的样式

layout_constraintVertical_chainStyle:竖直链条的样式

ConstraintLayout简单体验

实现类似RelativeLayout的效果

可以使用ConstraintLayout来实现,RelativeLayout的任意效果。使用相对性即可完美实现,这里另外使用偏移性(Bias)来实现水平靠左且垂直居于屏幕3/10处
ConstraintLayout简单体验

如果想要将控件在水平方向偏向左、或者在竖直方向偏向一个方向,就可以配合使用bias属性:

水平方向的偏移设置使用layout_constraintHorizontal_bias,垂直方向的偏移设置使用layout_constraintVertical_bias。居中情况下,bias的默认值为0.5,取值范围是0~1,是以left或top为始起边界。

实现类似FrameLayout的效果

可以使用ConstraintLayout来实现,FrameLayout的任意效果。这里使用Circular positioning(圆形定位)来实现A居中B位于A右侧上方30度

ConstraintLayout简单体验

相关属性

  • layout_constraintCircle:参照控件的id
  • layout_constraintCircleRadius:两个控件中心连线的距离
  • layout_constraintCircleAngle:当前View的中心与目标View的中心的连线与Y轴方向的夹角(取值:0~360)。

实现类似TabLayout的效果

可以使用ConstraintLayout来实现,TabLayout的任意效果。这里使用Percent dimension(百分比性)来实现水平2个button平分父布局的宽度
ConstraintLayout简单体验

更多

具体更多特性,请自行查看官方文档

参考:

https://developer.android.com/reference/android/support/constraint/ConstraintLayout

https://www.jianshu.com/p/106e4282a383

https://www.jianshu.com/p/a74557359882

https://blog.csdn.net/lmj623565791/article/details/78011599

https://blog.csdn.net/guolin_blog/article/details/53122387

相关文章:

  • 2022-12-23
  • 2021-05-24
  • 2022-03-05
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-07
  • 2021-12-20
  • 2022-02-10
  • 2021-07-08
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案