如何摆脱此约束警告消息?

时间:2019-08-15 07:48:18

标签: android android-studio android-layout android-xml android-styles

我有这个布局文件:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_view"
        style="@style/TextViewStyle"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

TextViewStyle样式是:

<style name="TextViewStyle">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="layout_constraintStart_toStartOf">parent</item>
</style>

如您所见,水平约束在样式文件中设置,垂直约束在布局文件中设置。尽管设置了两个约束,但Android Studio抱怨:

  

此视图不受水平约束:在运行时,除非您添加水平约束,否则它将跳至左侧

据我所知,它没有从样式文件中看到约束。我该怎么解决?

1 个答案:

答案 0 :(得分:0)

我已经运行了您的代码,它按定义正确运行。棉绒仅从一个文件即布局xml的角度看到错误,因此它显示错误。它可能会分散注意力,因此抑制它可能是一个好主意。但是我们必须以某种方式抑制它,以免对xml文件的其他部分发出警告。

幸运的是android有这样的工具。 您可以使用tools:ignore禁止来自xml元素的任何警告。 请参阅android文档here

正如文档所述,“此属性接受用逗号分隔的皮棉问题ID的列表,您希望工具在此元素或其任何相关项上忽略它们。”

只需将鼠标悬停在任何警告/错误等上方,然后按Ctrl + 1。您将在底部看到带有“ issue id”的警告的详细信息。 注意此问题ID。然后在您的xml布局中抑制您的警告,如下所示:

tools:ignore="your error issue id">

注意:要使用工具,您将必须在xml中定义工具。

xmlns:tools="http://schemas.android.com/tools"

为警告起见,您可以使用tools:像这样忽略:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        tools:ignore="MissingConstraints"
        android:id="@+id/text_view"
        style="@style/TextViewStyle"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

您的警告将消失。