android - TextInputLayout setError 方法在 24.2.0 中抛出 ClassCastException

标签 android android-design-library android-textinputlayout

我将支持库版本更新到 24.2.0,我的注册屏幕现在已经死了。问题出在 TextInputLayout 上,我有两种方法:

    protected void setError(@Nullable CharSequence errorMsg, @NonNull EditText editText, boolean forceClean) {
        TextInputLayout viewParent = (TextInputLayout) editText.getParent();
        if (forceClean) {
            viewParent.setErrorEnabled(false);
            viewParent.setError(null);
        }
        viewParent.setErrorEnabled(true);
        viewParent.setError(errorMsg);
    }

    protected void clearError(@NonNull EditText editText) {
        TextInputLayout viewParent = (TextInputLayout) editText.getParent();
        viewParent.setErrorEnabled(false);
        viewParent.setError(null);
    }

当我尝试将 EditText 的父级转换为 TextInputLayout 时出现错误,在布局中我有这样的代码:

<android.support.design.widget.TextInputLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

     <android.support.design.widget.TextInputEditText
          android:id="@+id/login_registration_firstname"
          style="@style/registration_form_field"
          android:hint="@string/login_registration_firstname"
          android:inputType="textCapWords" />
</android.support.design.widget.TextInputLayout>

所以,这工作得很好,但现在它抛出 ClassCastException:

java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.design.widget.TextInputLayout

我想知道是否有关于此的一些新指南?

最佳答案

问题调查表明由于某种原因有额外的布局,所以现在我们有 TextInputLayout -> FrameLayout -> TextInputEditText 这很可悲 :( 所以作为临时解决方法,我创建了以下方法:

@Nullable
private TextInputLayout getTextInputLayout(@NonNull EditText editText) {
        View currentView = editText;
        for (int i = 0; i < 2; i++) {
            ViewParent parent = currentView.getParent();
            if (parent instanceof TextInputLayout) {
                return (TextInputLayout) parent;
            } else {
                currentView = (View) parent;
            }
        }
        return null;
}

这将在 View 层次结构中找到您的 TextInputLayout。

如果你幸运的话,你会注意到这个粉红色的错误颜色变化,克服它的简单方法是在 styles.xml 中覆盖样式:

<style name="TextAppearance.Design.Error" parent="TextAppearance.AppCompat.Caption" tools:override="true">
        <item name="android:textColor">@color/red</item>
</style>

关于android - TextInputLayout setError 方法在 24.2.0 中抛出 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39149787/

相关文章:

android - 此应用程序未获得许可。请从android中的Android Market购买

android - 从 PowerShell 使用 System.IO 访问 MTP 存储

android - 让两种口味使用同一个sourceSet

android - 如果项目 View 中有 Button,则 onItemClick 不起作用

android - 通过滚动隐藏后以编程方式显示工具栏(Android 设计库)

android - 在 XML 中添加 Material 按钮导致应用程序崩溃

java - Android L - float 操作按钮 (FAB)

android - 删除 TextInputLayout 额外的顶部填充

安卓|使用 styles.xml 更改 TextInputLayout 的主题

android - 以编程方式更改 TextInputLayout 轮廓框颜色