TextInputLayout setErrorEnabled 不创建新的 TextView 对象

TextInputLayout setErrorEnabled doesn't create new TextView object

我在创建登录表单时发现了一个问题。当用户正确填写内容时,我在 TextInputLayout 上显示了一些错误并禁用了它们。

我设置为

mTextInputLayout.setError("This field is required");

并使用

禁用它
mTextInputLayout.setError(null);

问题是空 TextView 对象仍有填充,显示错误消息。所以我尝试通过设置

完全禁用错误
mTextInputLayout.setErrorEnabled(false);

它工作正常,看起来不错,但我无法再次打开它。调用时

mTextInputLayout.setErrorEnabled(true);
mTextInputLayout.setError("This field is required");

同样,我只看到了一条读取行,而不是错误消息,因此显示错误消息的 TextView 似乎已被销毁并且不再创建。

我读到 here,当调用 setErrorEnabled(false) 时,TextView 对象被销毁并且似乎没有再次创建。错误或功能?

The source for this control is not yet available in AOSP so I used the decompiler built in to Android Studio to examine the code to understand what was going wrong. I found that setErrorEnabled() actually creates and destroys a TextView object, whereas I was expecting it to simply toggle the visibility.

如果有人遇到同样的问题,我找到了一个工作正常的解决方法。 只需将错误TextView对象的可见性设置为开和关即可,不要破坏对象。

使用它来启用错误消息:

if (textInputLayout.getChildCount() == 2)
    textInputLayout.getChildAt(1).setVisibility(View.VISIBLE);

textInputLayout.setError("This field is required");

这用于禁用错误消息:

textInputLayout.setError(null);

if (textInputLayout.getChildCount() == 2)
    textInputLayout.getChildAt(1).setVisibility(View.GONE);

从支持库版本 23.1.1(可能更早)开始,调用 setErrorEnabled(false) 将删除错误 TextView 并导致 TextInputLayout 在随后调用 setError(String) 时显示新错误。

但是,仍然存在错误消息清除后未从布局中删除额外填充的错误。这个错误可以通过使用上面@dabo 的 post 来解决:

https://code.google.com/p/android/issues/detail?id=200137

在我的情况下设置错误,清除错误和设置错误再次导致错误。一条线没有再次变红 (API 23.4.0)。此解决方案帮助:

setError(null) 之后调用 setErrorEnabled(false)