ConstraintLayout 学习笔记

来源:互联网 发布:radiohead知乎 编辑:程序博客网 时间:2024/06/06 12:21

如何阅读 xml 属性

与 Relativelayout 不同,ConstrainLayout 的属性需要同时说明需要怎么操作自己与目标控件,例如:layout_constraintLeft_toLeftOf 指自身左边缘与目标控件左边缘对齐

从此 match_parent 是故人

ConstraintLayout 里不再使用 match_parent,想要铺满屏幕,只能设置宽度为 0,并添加左右边缘与父容器的约束。(* 想要实现 match_parent的效果,切记要设置该方向大小为 0dp *

android:layout_width="0dp"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"

穿了马甲的 LinearLayout

线性布局的 weight 属性可以轻松实现等分操作。在 ConstraintLayout 里你也可以实现类似的功能:

app:layout_constraintHorizontal_bias=".3" //数值范围:0~1

如果控件已约束了左右边缘且定义了 bias 为 0.3,则意味着控件与左边缘的距离占控件左右边缘间距的 30%,如图:

bias

甚至想要实现 LinearLayout 的 weight=1 等分操作(例如水平方向上等分)也很简单,每个相邻控件互为约束并设置 width=0dp 即可。这样其实就组成了链(chaining)。

像上面说到的,设置 width=0,且控件之间两两互相约束,即可实现水平方向等分。此时还可以给控件设置 layout_constraintHorizontal_weight 属性,该属性与 LinearLayout 中的 weight 类似。

链条头部的属性

水平链的最左边,垂直链的最上边称之为头部,链的头部可以设置链的属性:

app:layout_constraintHorizontal_chainStyle="spread" app:layout_constraintVertical_chainStyle="packed"
  • spread 默认属性,平均分布
  • spread_inside 首尾无间距
  • packed 控件间无间距,可以同时搭配 layout_constraintHorizontal_bias 属性控制与父容器的间距

各属性值的样式如下:

各属性样式

厉害了,还能设宽高比

app:layout_constraintDimensionRatio="1:1" //宽:高

该属性起作用的前提是宽或高至少有一个设为 0dp,设为 0dp 的边即为随比例缩放的边。
举个栗子:

 <TextView    android:layout_width="wrap_content"    android:layout_height="0dp"    app:layout_constraintDimensionRatio="1:1"/>

该文本框在随着内容文字的增加,宽度会越来越大,一旦设定了宽高比为1,则在宽度增大时高度也会等比增大,一直保持在宽高比1:1。

宽高比还有另外的妙用,比如一个控件左右边缘已存在与父容器约束,且同时将宽高都设为 0dp,便得到水平方向上铺满屏幕的效果,如图:

宽高均设为0

指示线 Guideline

指示线不会被绘制到 UI 中,所以放心大胆地用。Guideline 的一些属性:

  <android.support.constraint.Guideline    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/guideline"    app:layout_constraintGuide_percent="0.5" //设置位置比例    android:orientation="vertical"/> //不注明该属性,则默认是水平方向    app:layout_constraintGuide_begin="30dp" //设置与头部边距    app:layout_constraintGuide_end="30dp" // 设置与尾部边距

其他

  • layout_goneMarginLeft 属性,当有约束关系的控件被置为 gone 状态时,可以通过设置该属性来控制间距

动画

[译]Constraint Layout 动画 |动态 Constraint |用 Java 实现的 UI(这到底是什么)[第三部分]