如何在Constraint Layout中固定按钮于底部?
如何在ConstraintLayout中固定按钮到底部
当然可以实现,你之前用Vertical Bias没效果是因为用错了场景——Bias是用来调整同时存在上下/左右约束时的位置比例,而固定到底部根本不需要给按钮加顶部约束,只需要绑定底部约束就行。
下面是两种实现方式:
可视化布局编辑器操作
- 选中要固定的按钮
- 在右侧属性面板的「Constraints」区域,点击底部的约束图标(向下箭头),将按钮底部与ConstraintLayout的底部绑定
- 如果需要水平居中,再点击左右的约束图标,把按钮的左右边缘和父布局的左右边缘绑定,或者直接点击「Horizontal Center」快速添加居中约束
XML代码实现示例
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/fixed_bottom_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="底部固定按钮" <!-- 核心约束:按钮底部绑定父布局底部 --> app:layout_constraintBottom_toBottomOf="parent" <!-- 可选:水平居中约束 --> app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性解释:
app:layout_constraintBottom_toBottomOf="parent":这是固定按钮到底部的核心,直接让按钮底部和父布局底部对齐- 如果不需要水平居中,只保留底部约束即可,还可以通过
app:layout_constraintStart_toStartOf="parent"(靠左)或app:layout_constraintEnd_toEndOf="parent"(靠右)调整水平位置
内容的提问来源于stack exchange,提问作者Sakshi Sinha
相关产品推荐
相关产品推荐

