TextInputLayout setErrorEnabled doesn't create

2019-04-05 12:19发布

I've found an issue while creating a login form. I show some errors on my TextInputLayout and disable them, when the user filled in something correctly.

error example

I set it with

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

and disable it with

mTextInputLayout.setError(null);

Problem is that there are still paddings of the empty TextView object, which was showing the error message. So I tried to disable the error completely with setting

mTextInputLayout.setErrorEnabled(false);

and it works and looks fine, BUT I can't set it on again. When calling

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

again I just see a read line, NOT the error message, so it seems the TextView which was showing the error message was destroyed and not created again.

I read here, that the TextView objects gets destroyed, when setErrorEnabled(false) is called and it seems it is not created again. Bug or feature?

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.

3条回答
成全新的幸福
2楼-- · 2019-04-05 12:57

In my case setting error, clearing error and setting error again caused a bug. A line hasn't become red again (API 23.4.0). This solution helped: TextInputLayout.setError() leaves empty space after clearing the error

Call setErrorEnabled(false) after setError(null).

查看更多
贪生不怕死
3楼-- · 2019-04-05 13:12

In case someone faces the same problem, I found a workaround that works fine. Just set the visibility of the error TextView object on and off, don't destroy the object.

Use this for enabling the error message:

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

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

and this for disabling the error message:

textInputLayout.setError(null);

if (textInputLayout.getChildCount() == 2)
    textInputLayout.getChildAt(1).setVisibility(View.GONE);
查看更多
姐就是有狂的资本
4楼-- · 2019-04-05 13:20

As of Support library version 23.1.1 (and perhaps earlier), calling setErrorEnabled(false) will remove the error TextView and cause the TextInputLayout to display a new error when setError(String) is subsequently called.

However, there is still an existing bug where additional padding is not removed from the Layout once the error message is cleared. This bug can be worked around by using @dabo's post above:

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

查看更多
登录 后发表回答