Android ConstraintLayout中Vertical Bias与Horizontal Bias的作用是什么
ConstraintLayout 中 Vertical Bias 与 Horizontal Bias 的作用
这两个属性是ConstraintLayout独有的位置调整属性,仅在控件对应方向存在双向约束时生效(比如垂直方向同时设置了top和bottom方向的约束,水平方向同时设置了start和end方向的约束),作用是调整控件在两个约束锚点形成的可用区间内的相对位置,默认值均为0.5,也就是控件在区间内居中。
Horizontal Bias(水平偏移)
- 作用对象:水平方向的约束区间
- 取值范围:0~1之间的浮点数
- 取值为
0:控件完全贴紧水平方向起始端的约束锚点(受系统布局方向影响,LTR布局下为左侧,RTL布局下为右侧) - 取值为
1:控件完全贴紧水平方向结束端的约束锚点 - 常见用法举例:给控件同时加了
app:layout_constraintStart_toStartOf="parent"和app:layout_constraintEnd_toEndOf="parent"两个约束时,将app:layout_constraintHorizontal_bias设为0.8,就代表控件距离水平起始端的空白占总可用空白的80%,距离结束端占20%,整体靠向结束端。
- 取值为
Vertical Bias(垂直偏移)
- 作用对象:垂直方向的约束区间
- 取值范围:0~1之间的浮点数
- 取值为
0:控件完全贴紧顶部的约束锚点 - 取值为
1:控件完全贴紧底部的约束锚点 - 常见使用场景:要实现控件在父布局垂直方向上1/3偏上的位置,不需要写死margin,只要给控件加
app:layout_constraintTop_toTopOf="parent"和app:layout_constraintBottom_toBottomOf="parent"双向约束,再把app:layout_constraintVertical_bias设为0.33即可。
- 取值为
示例代码
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/demo_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="演示按钮" <!-- 双向约束是Bias生效的前提 --> app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" <!-- 水平偏左20%,垂直偏上30% --> app:layout_constraintHorizontal_bias="0.2" app:layout_constraintVertical_bias="0.3" /> </androidx.constraintlayout.widget.ConstraintLayout>
注意事项
如果控件在对应方向仅设置了单向约束,设置Bias属性不会生效,属于无效配置。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

