Android Studio - 如何解决这个视图不受约束的错误

717 阅读2分钟

每当你在ConstraintLayout 视图组中添加一个AndroidView ,你可能会看到Android Studio给出的错误信息,如下图所示,This view is not constrained

This view is not constrained.
It only has designtime positions, so it will jump to (0,0)
at runtime unless you add the constraints

这是因为一个ConstraintLayout 要求布局内的任何子View 至少有一个水平和一个垂直的约束 View

在下面的截图中,添加到布局中的Button 视图导致了这个错误。

你可以点击图片使其放大:

Android Studio this view is not constrained error

Android Studio这个视图没有被约束的错误

(android-studio-constraint-layout-error.png)

为了解决这个错误,你需要给Button 视图添加约束,满足ConstraintLayout 视图的最低要求。

你可以通过两种方式做到这一点:

  • 使用 "设计"窗口工具栏中的 "推断约束"选项
  • 使用View's context menu中的Constrain选项。

Infer Constraints !选项用于让Android Studio扫描布局并确定所有视图的最有效约束集。

你可以从设计窗口的工具栏上点击该按钮,如下图所示:

Android Studio Infer Constraints button position

Android Studio Infer Constraints按钮位置

(android-studio-infer-constraints-toolbar.png)

该选项将影响所有在你当前布局中没有约束的视图。

在旧的Android Studio版本中(版本2及以下),可以在你的视图的上下文菜单中访问Infer Constraints选项。

右键点击有错误信息的View ,选择Infer Constraints,如下图所示:

Android Studio v2 Infer Constraints option

Android Studio v2 Infer Constraints选项

(android-studio-v2-infer-constraints.png)

除了Infer Constraints选项,你还可以使用Constrain选项来给View 对象添加约束。

用Constrains选项添加约束

约束选项允许你手动添加一个约束角度到你的View 对象。

你需要右键点击有错误信息的View ,如下图所示:

Android Studio Constrains option

Android Studio的约束选项

(android-studio-constrains-option.png)

有四个约束,你可以添加到View

  • parent top 和 添加一个垂直约束到parent bottom View
  • parent start 和 ,在 "D "中添加了一个水平约束。parent end View

你只需要在每个角度中添加一个来解决错误。

在下面的截图中,parent startparent bottom 的约束被添加到Button 视图中:

Android Studio resolve constraint error

Android Studio解决约束错误

(android-studio-resolve-constrain-error.png)

有了这个,错误信息应该从你的View 对象中消失。

这就是你在开发Android应用程序时如何解决This view is not constrained 错误👍