Android TextInputLayout cambia el estilo de EditText después de establecer el error en null
Por primera vez estoy usando el nuevo widget de Android TextInputLayout, es muy bonito pero estoy enfrentando algún problema usando el método setError
Este es mi xml
- Reaccione Nativo. ¿Cómo puedo mantener el foco en una entrada de texto cuando la página vuelve a aparecer en la marca del temporizador
- Cómo hacer que TextInputLayout asigne rojo asterisco para los campos obligatorios
- Medir la altura del contenedor de errores TextInputLayout
- Icono de la izquierda en TextInputLayout
- Problema con la alineación mediante TextInputLayout y Spinner
<android.support.design.widget.TextInputLayout android:id="@+id/userData_txtNameWrapper" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:textColorHint="@color/light_gray" app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout"> <EditText android:id="@+id/userData_txtName" style="@style/bold_textbox_style" android:layout_width="match_parent" android:layout_height="@dimen/textinut_height" android:layout_margin="5dp" android:hint="name" android:imeOptions="actionNext" android:inputType="text" android:paddingTop="10dp" android:textSize="@dimen/medium_text"/> </android.support.design.widget.TextInputLayout>
QUE ESTA PASANDO:
Cuando corro
setError("error message")
El fondo entero de EditText y el color del texto de la indirecta se vuelven rojos y puesto que aquí está muy bien. El problema es cuando corro
setError(null)
El estilo del EditText se cambia completamente del original.
SITUACIÓN DE INICIO:
desenfocado Enfocado
AFTER setError("mandatory field")
AFTER setError(null)
Hice un montón de investigaciones, pero no pude encontrar nada útil, ¿qué demonios debería ser el problema?
ACTUALIZAR
Investigar en el código fuente android del método setError()
encontré esto
public void setError(@Nullable CharSequence error) { if (!mErrorEnabled) { if (TextUtils.isEmpty(error)) { // If error isn't enabled, and the error is empty, just return return; } // Else, we'll assume that they want to enable the error functionality setErrorEnabled(true); } if (!TextUtils.isEmpty(error)) { ViewCompat.setAlpha(mErrorView, 0f); mErrorView.setText(error); ViewCompat.animate(mErrorView) .alpha(1f) .setDuration(ANIMATION_DURATION) .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationStart(View view) { view.setVisibility(VISIBLE); } }) .start(); // Set the EditText's background tint to the error color mErrorShown = true; updateEditTextBackground(); updateLabelVisibility(true); } else { if (mErrorView.getVisibility() == VISIBLE) { ViewCompat.animate(mErrorView) .alpha(0f) .setDuration(ANIMATION_DURATION) .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationEnd(View view) { view.setVisibility(INVISIBLE); updateLabelVisibility(true); } }).start(); // Restore the 'original' tint, using colorControlNormal and colorControlActivated mErrorShown = false; updateEditTextBackground(); } } private void updateEditTextBackground() { if (mErrorShown && mErrorView != null) { // Set the EditText's background tint to the error color ViewCompat.setBackgroundTintList(mEditText, ColorStateList.valueOf(mErrorView.getCurrentTextColor())); } else if (mCounterOverflowed && mCounterView != null) { ViewCompat.setBackgroundTintList(mEditText, ColorStateList.valueOf(mCounterView.getCurrentTextColor())); } else { final TintManager tintManager = TintManager.get(getContext()); ViewCompat.setBackgroundTintList(mEditText, tintManager.getTintList(R.drawable.abc_edit_text_material)); } }
Y depurar el código encontré que el pedazo de código que se ejecuta en updateEditTextBackground()
es el siguiente
final TintManager tintManager = TintManager.get(getContext()); ViewCompat.setBackgroundTintList(mEditText, tintManager.getTintList(R.drawable.abc_edit_text_material));
Parece que android es arbitrario reemplazar el matiz de fondo del EditText. Intenté crear un archivo en mi carpeta drawable nombrado abc_edit_text_material.xml con este código
<inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material" android:insetRight="@dimen/abc_edit_text_inset_horizontal_material" android:insetTop="@dimen/abc_edit_text_inset_top_material" android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"> <selector> <item android:state_enabled="false" android:drawable="@color/white"/> <item android:state_pressed="false" android:state_focused="false" android:drawable="@color/white"/> <item android:drawable="@color/white"/> </selector> </inset>
Pero este es el resultado después de setError(null)
Por otra parte noté que el problema existe solamente cuando ejecuto setError ("mensaje de error") y entonces setError (null)
UPDATE 2 Este es el código que utilizo para validar mis entradas
public boolean validateInputs() { mTxtNameWrapper.setError(null); mTxtLastNameWrapper.setError(null); mTxtEmailWrapper.setError(null); mTxtCountryWrapper.setError(null); mTxtIdCardWrapper.setError(null); mTxtFiscalCodeWrapper.setError(null); mLblDocTypeError.setVisibility(View.GONE); if (Strings.isNullOrEmpty(mTxtName.getText().toString())) { mTxtNameWrapper.setError("Mandatory field"); return false; } if (Strings.isNullOrEmpty(mTxtLastName.getText().toString())) { mTxtLastNameWrapper.setError("Mandatory field"); return false; } if (Strings.isNullOrEmpty(mTxtEmail.getText().toString())) { mTxtEmailWrapper.setError("Mandatory field"); return false; } if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mTxtEmail.getText().toString()).matches()) { mTxtEmailWrapper.setError("Invalid email format"); return false; } if (Strings.isNullOrEmpty(mTxtCountry.getText().toString())) { mTxtCountryWrapper.setError("Mandatory field"); return false; } if (mRdgIdType.getCheckedRadioButtonId() == -1) { mLblDocTypeError.setText("Select a document type"); mLblDocTypeError.setVisibility(View.VISIBLE); return false; } if (Strings.isNullOrEmpty(mTxtIdCard.getText().toString())) { mTxtIdCardWrapper.setError("Mandatory field"); return false; } if (Strings.isNullOrEmpty(mTxtFiscalCode.getText().toString())) { mTxtFiscalCodeWrapper.setError("Mandatory field"); return false; } return true; }
¡¡¡Me estoy volviendo loco!!!
- TextInputLayout no se muestra cuando se agrega programativamente
- ImeOption = "actionNext" no funciona en TextInputLayout.
- TextInputLayout método setError lanza ClassCastException en 24.2.0
- Sugerencia de EditText visibile while transition
- Cómo cambiar el tamaño de la pista de TextInputLayout
- Android TextInputLayout Cambiar contraseña no visible en la nueva biblioteca de soporte
- Mantener TextInputLayout siempre enfocado o mantener la etiqueta siempre expandida
- Deshabilitar / quitar texto de sugerencia de etiqueta flotante en TextInputLayout XML
Sólo tienes que cambiar el color de nuevo a lo que quieras después de configurar el error a null. Algo como:
yourEditText.setError(null); yourEditText.getBackground().mutate().setColorFilter( ContextCompat.getColor(getContext() , R.color.somecolor), PorterDuff.Mode.SRC_ATOP);
Se trataba de un error en support:design:23.2.0
(y posiblemente versiones anteriores) se informó como un problema aquí y se ha corregido en la actualización 23.3.0
Me encontré con un problema similar y encontré una solución simple para ello. Este problema se produce si establecemos un fondo personalizado drawable / color a la EditText
dentro de TextInputLayout
. Solución a esto sería subclase el TextInputLayout
y reemplazar los setError()
y setError()
y establecer nuestro personalizado drawable / color como el fondo EditText's
nuevo. Por ejemplo, yo tenía un conjunto redondeado de esquina EditText's
fondo de mi EditText's
, a continuación es mi subclase,
public class RoundedBorderedTextInputLayout extends TextInputLayout { private Context context; public RoundedBorderedTextInputLayout(Context context) { super(context); this.context = context; } public RoundedBorderedTextInputLayout(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public RoundedBorderedTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); EditText editText = getEditText(); if(editText != null) { editText.setBackground(ContextCompat.getDrawable(this.context, R.drawable.custom_rounded_edittext)); } } @Override public void setError(@Nullable final CharSequence error) { super.setError(error); EditText editText = getEditText(); if(editText != null) { editText.setBackground(ContextCompat.getDrawable(this.context, R.drawable.custom_rounded_edittext)); } } }
Y luego utilizar su clase personalizada en el xml,
<com.example.RoundedBorderedTextInputLayout android:id="@+id/text_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword"/> </com.example.RoundedBorderedTextInputLayout>
Espero que esto ayude. Happy Android codificación 🙂
Establecer el estilo de la entrada de texto
<style name="TextAppearence.App.TextInputLayout" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/colorPrimaryDark</item> <item name="android:textColorHint">@color/colorPrimaryDark</item> <item name="android:textSize">14sp</item> <item name="colorAccent">@color/colorPrimaryDark</item> <item name="colorControlNormal">@color/colorPrimaryDark</item> <item name="colorControlActivated">@color/colorPrimaryDark</item> </style>
Ponga debajo del código donde se estableceError (null)
txt.setError(null); //for plain white backgorund editText.setBackgroundColor(getResources().getColor(android.R.color.white)); //or if you want any other than editText.setBackgroundResource(R.drawable.border);
Donde border es mi xml
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> <stroke android:width="2dp" android:color="#ff207d94" /> <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" /> <corners android:radius="5dp" /> <solid android:color="#ffffffff" /> </shape>
Tengo un truco para resolver este problema simplemente:
1, una nueva clase extiende android.support.design.widget.TextInputEditText; 2, método overrvide getBackground (), devolverlo nulo;
Porque el método updateEditTextBackground () en TextInputLayout juzgará si el fondo de editText dibujable es nulo, y ahora siempre devuelve null, el resultado es el fondo de editText no será cambiado por el color de texto de error.
- En una aplicación de Android, ¿debo tener un proveedor de contenido por tabla o sólo uno para toda la aplicación?
- Limpiar por defecto algunas toallitas con jQuery touchwipe