如何在ConstraintLayout中让按钮居底且关联上方EditText组件?
这个需求完全可以实现,直接调整约束就能搞定
不用设置固定marginTop,靠ConstraintLayout的约束就能把按钮稳稳钉在屏幕底部,同时保证和上方的EditText不会出现布局错乱。具体修改步骤如下:
调整按钮的约束:
- 删掉按钮原来的
app:layout_constraintTop_toBottomOf="@+id/editText2" - 添加
app:layout_constraintBottom_toBottomOf="parent",把按钮锚定到屏幕底部 - 补充
app:layout_constraintEnd_toEndOf="parent",确保按钮横向铺满父布局(和EditText对齐)
- 删掉按钮原来的
给第二个EditText添加底部约束:
- 给
editText2加上app:layout_constraintBottom_toTopOf="@id/editBtn",让它和按钮顶部建立关联,这样无论屏幕高度怎么变,两者之间都会自动留出合适的间距,不会重叠
- 给
修改后的完整XML代码:
<EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLength="20" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLength="20" app:layout_constraintTop_toBottomOf="@+id/editText1" app:layout_constraintBottom_toTopOf="@id/editBtn" /> <Button android:id="@+id/editBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:enabled="false" android:text="Edit" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" />
为什么这么改:
- 用
constraintBottom_toBottomOf="parent"直接把按钮固定在屏幕底部,完全不依赖marginTop,适配所有设备屏幕高度 - 给
editText2和按钮加约束,让系统自动处理中间的间距,不管屏幕是大是小,布局都不会错乱或重叠 - 保留EditText的顶部约束,让它们始终保持在屏幕上方的排列顺序
内容的提问来源于stack exchange,提问作者Nikitha
相关产品推荐
相关产品推荐

