转载This view is not constrained, it only has designti AS报错

解决Android Studio视图定位错误
本文介绍了解决Android Studio中视图定位错误的方法。当视图在编辑时位置不正确,但在运行时跳转到(0,0)时,可以通过使用Design界面下的魔棒工具InferConstraints来重新设置视图的约束。

This view is not constrained  Android Studio报错

这个视图只是编辑时位置,在运行时视图会跳转到(0,0)

解决办法:在Design界面下,有个魔棒工具,Infer Constrains,点击选择约束

 

这个错误信息: > **"This view is not constrained. It only has designtime positions, so it will jump to (0,0) at runtime unless you add the constraints"** 是 Android Studio 的 **ConstraintLayout 布局检查警告**,表示你在 `ConstraintLayout` 中添加了一个控件,但它 **没有设置任何约束(constraints)**,所以在 **运行时会跑到左上角 (0,0) 的位置**,而不是你在设计视图中看到的位置。 --- ### 🔍 错误原因 在 `ConstraintLayout` 中,**所有子视图都必须通过约束来定义其位置**,否则它们在运行时不会按照你在编辑器中拖放的位置显示。 --- ### ✅ 解决方案 你需要为该控件设置 **至少两个约束(水平 + 垂直)**,例如: ```xml <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> ``` 上面这个按钮约束了: - 左边(`Start`)对齐父布局的左边 - 上边(`Top`)对齐父布局的上边 这样它在运行时就会显示在左上角。 --- ### ✅ 常见修复方式 | 控件 | 修复方法 | |------|----------| | 单个控件 | 至少设置两个方向的约束(如 `top` + `start`) | | 水平居中 | `app:layout_constraintStart_toStartOf="parent"` + `app:layout_constraintEnd_toEndOf="parent"` | | 垂直居中 | `app:layout_constraintTop_toTopOf="parent"` + `app:layout_constraintBottom_toBottomOf="parent"` | | 依赖其他控件 | 使用 `app:layout_constraintTop_toBottomOf="@id/another_view"` 等方式约束到其他控件 | --- ### 🛠 示例:修复未约束的 TextView 错误代码: ```xml <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="未约束的文本" /> ``` 修复后: ```xml <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="已约束的文本" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/anotherView" app:layout_constraintBottom_toBottomOf="parent" /> ``` --- ### 💡 小技巧:使用 Android Studio 自动添加约束 1. 在 **Design 视图**中选中未约束的控件 2. 右键点击 → **Center** 或 **Inference Constraints** 3. 或者点击顶部工具栏的 **"Infer Constraints"** 按钮(魔术棒图标) --- ### ✅ 总结 | 问题 | 原因 | 解决方案 | |------|------|----------| | 控件位置异常 | 没有约束 | 添加 `layout_constraintXXX` | | 控件跑到左上角 | 未设置任何约束 | 设置至少两个方向的约束 | | 使用 ConstraintLayout 必须约束 | 是的 | 是的 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值