【问题标题】:TextInputLayout setErrorEnabled doesn't create new TextView objectTextInputLayout setErrorEnabled 不会创建新的 TextView 对象
【发布时间】:2016-01-18 18:09:35
【问题描述】:

我在创建登录表单时发现了一个问题。当用户正确填写内容时,我会在 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 对象被破坏,并且似乎没有再次创建它。错误或功能?

此控件的源代码在 AOSP 中尚不可用,因此我使用 Android Studio 内置的反编译器检查代码以了解问题所在。我发现 setErrorEnabled() 实际上创建和销毁了一个 TextView 对象,而我期望它只是简单地切换可见性。

【问题讨论】:

    标签: android layout textview android-textinputlayout


    【解决方案1】:

    如果有人遇到同样的问题,我找到了一个可以正常工作的解决方法。 只需设置错误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);
    

    【讨论】:

    • 谢谢,我遇到了同样的问题。不知道为什么 Google 会这样实现,但是 setErrorEnabled(true) 无法按预期工作,这太可怕了 -> 如果我们之前调用了 setErrorEnabled(false),则在 setErrorEnabled(true) 之后错误不可见
    • 我面临 java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/internal/widget/TintManager;在 android.support.design.widget.TextInputLayout.setError(TextInputLayout.java:379) 在 textInputLayout.setError(null);
    • 您正在将 android 支持库导入到您的项目中(在您的 build.gradle 文件中)?依赖项 { 编译 'com.android.support:design:23.1.0' }
    • 如果您还使用计数器,textInputLayout.getChildAt(1) 可能会返回错误的视图。
    【解决方案2】:

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

    但是,仍然存在一个错误,即清除错误消息后,不会从布局中删除额外的填充。可以使用上面@dabo 的帖子解决此错误:

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

    【讨论】:

      【解决方案3】:

      在我的情况下设置错误,清除错误和设置错误再次导致错误。一条线没有再次变红(API 23.4.0)。这个解决方案有帮助:TextInputLayout.setError() leaves empty space after clearing the error

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多