我将支持库版本更新到 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/