<androidx.constraintlayout.widget.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MainActivity">

    <Button
        android:id="@+id/btn_go_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="前往测试" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • 在 Android 开发中,ConstraintLayout 中的视图出现如下警告信息
This view is not constrained. It only has designtime positions, so it will jump to (0,0) at runtime unless you add the constraints
问题原因
  • 视图缺少约束条件,只有设计时位置(designtime positions),运行时会跳到左上角 (0, 0)
  1. 当使用 ConstraintLayout 时,视图的位置必须通过约束来定义

  2. 如果只是在设计视图中拖拽移动了视图,但没有添加约束,Android Studio 会保存这些设计时位置用于预览,但运行时系统无法知道如何定位它

处理策略
  1. 添加约束,例如,添加水平和垂直约束
<Button
    android:id="@+id/btn_go_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="前往测试"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
  1. 或者,忽略警告信息(不推荐)
<Button
    android:id="@+id/btn_go_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="前往测试"
    tools:ignore="MissingConstraints" />

更多推荐