使用AVD运行后ConstraintLayout布局混乱,控件堆叠左上角
解决ConstraintLayout控件堆叠在屏幕左上角的问题
嗨,这个情况我太熟悉了!你之所以遇到控件全堆在左上角的问题,核心原因是你只用了tools:开头的属性来定位控件——这些属性只是给Android Studio的布局编辑器用的,实际运行时系统会完全忽略它们,你的控件没有任何真正的约束,自然都挤在默认位置(左上角)了,和ConstraintLayout的版本没关系哦。
看你的XML代码,所有控件的位置都是用tools:layout_editor_absoluteX/Y设置的,这只是编辑器里的预览位置,不是真正的布局约束。解决办法就是给每个控件添加app:开头的ConstraintLayout约束属性,让系统知道控件该怎么摆放。
给你修改后的完整XML代码,你可以直接替换试试:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.pc.myapplication.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="username" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintMarginStart="16dp" app:layout_constraintMarginTop="143dp" /> <EditText android:id="@+id/TFusername" android:layout_width="0dp" android:layout_height="40dp" android:ems="10" android:inputType="textPersonName" app:layout_constraintStart_toEndOf="@+id/textView" app:layout_constraintTop_toTopOf="@+id/textView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintMarginStart="16dp" app:layout_constraintMarginEnd="16dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="password" app:layout_constraintStart_toStartOf="@+id/textView" app:layout_constraintTop_toBottomOf="@+id/TFusername" app:layout_constraintMarginTop="32dp" /> <EditText android:id="@+id/TFpassword" android:layout_width="0dp" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" app:layout_constraintStart_toEndOf="@+id/textView2" app:layout_constraintTop_toTopOf="@+id/textView2" app:layout_constraintEnd_toEndOf="@+id/TFusername" app:layout_constraintMarginStart="16dp" /> <Button android:id="@+id/BLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" android:text="Login" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/TFpassword" app:layout_constraintMarginTop="32dp" /> </android.support.constraint.ConstraintLayout>
关键修改说明:
- 移除了所有
tools:layout_editor_absoluteX/Y属性,替换成app:layout_constraintXXX系列的真正约束属性 - 给EditText设置
layout_width="0dp",配合左右约束实现自适应宽度,能更好适配不同尺寸的屏幕 - 让控件之间通过
layout_constraintTop_toBottomOf等属性建立关联,保证布局的连贯性,不会错乱 - 添加了margin属性来控制控件间距,和你原本在编辑器里的位置效果一致
另外给你个小技巧:在Android Studio的布局编辑器里,选中所有控件后,点击右侧面板里的**"Infer Constraints"魔法棒图标**,编辑器会自动帮你生成合理的约束,不用手动写这么多代码,超级方便!
内容的提问来源于stack exchange,提问作者jalel
相关产品推荐
相关产品推荐

