错误消息间距在 TextInputLayout 大纲样式中不起作用

Error message spacing not working in TextInputLayout Outlined style

我正在尝试使用 MaterialComponents TextInputLayout 实现一个表单。根据 docs,它应该有一个 space 作为错误信息。我在我的布局 xml 中启用了错误消息,它也显示在 Android Studio 布局预览中,但在应用程序中不起作用。

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/name_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:hint="@string/hint_name">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimaryText"
            android:singleLine="true" />

    </com.google.android.material.textfield.TextInputLayout>

预览:

实际发生了什么:

我通过在输入有效时禁用它后立即启用 errorMessage 来修复它。

    else {  // Condition finally met when error is valid
        signinEmailLayout.setErrorEnabled(false);
        signinEmailLayout.setErrorEnabled(true);
    }

正如@MRamzan 在评论中所建议的那样,这似乎是默认行为。无论如何,在我的 activity class 中,我将 errorEnabled 设置为 false,这导致布局在输入有效时删除指定用于错误消息的 space。一旦输入再次无效,就会添加错误消息,因为我再次启用它,因此存在不稳定的用户体验。

设置 app:errorEnabled="true" 将修改布局以保留 space 以便显示错误文本。问题是您正在设置 errorEnabled=false 以隐藏删除错误文本的 space 的错误。

而是始终保留 errorEnabled=true 并使用 TextInputLayout#error 来显示和隐藏错误。

// Shows error text and UI
nameInputLayout.error = getString(R.string.error)

// Hides error text and UI
nameInputLayout.error = null

请参阅“向文本字段添加错误”下的 https://material.io/components/text-fields/android#using-text-fields