Limite la longitud del texto de EditText en Android
¿Cuál es la mejor manera de limitar la longitud de texto de un EditText
en Android?
¿Hay una manera de hacer esto vía xml?
- Android EditText insertar
- Cómo limitar la longitud de EditText a 7 enteros y 2 decimales?
- ¿Hay alguna manera de definir un valor mínimo y máximo para EditText en Android?
- EditText texto claro en el primer foco - Android
- Pegar sin formato de texto enriquecido en EditText
- ¿Cómo mostrar la lista desplegable debajo de EditText?
- Cómo hacer android EditText más pequeño que el valor predeterminado en la altura?
- Soporte de RTL para editext personalizado para izquierda dibujable
- Cómo desactivar el posicionamiento del cursor y la selección de texto en un EditText? (Androide)
- RequestFocus no funciona
- Establecer imagen en el lado izquierdo de EditText en Android
- ¿Cómo puedo añadir una imagen en EditText
- ¿Cómo verificar la tarjeta PAN?
Documentación
Ejemplo
android:maxLength="10"
Utilice un filtro de entrada para limitar la longitud máxima de una vista de texto.
TextView editEntryView = new TextView(...); InputFilter[] filterArray = new InputFilter[1]; filterArray[0] = new InputFilter.LengthFilter(8); editEntryView.setFilters(filterArray);
EditText editText = new EditText(this); int maxLength = 3; editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Una nota para las personas que ya están utilizando un filtro de entrada personalizada y también quieren limitar la longitud máxima:
Cuando se asignan filtros de entrada en el código se borran todos los filtros de entrada establecidos previamente, incluyendo un conjunto con android: maxLength. Encontré esto al intentar utilizar un filtro de entrada personalizado para evitar el uso de algunos caracteres que no permitimos en un campo de contraseña. Después de establecer ese filtro con setFilters, la maxLength ya no se observó. La solución era establecer maxLength y mi filtro personalizado juntos mediante programación. Algo como esto:
myEditText.setFilters( new InputFilter[] { new PasswordCharFilter(), new InputFilter.LengthFilter(20)});
Solo para Android:
TextView tv = new TextView(this); tv.setFilters(new InputFilter[] { new InputFilter.LengthFilter(250) });
Para cualquier otra persona que se pregunta cómo alcanzar esto, aquí está mi clase extendida de EditText
EditTextNumeric
.
.setMaxLength(int)
– establece el número máximo de dígitos
.setMaxValue(int)
– límite del valor entero máximo
.setMin(int)
– valor mínimo entero de límite
.getValue()
– obtener valor entero
import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.widget.EditText; public class EditTextNumeric extends EditText { protected int max_value = Integer.MAX_VALUE; protected int min_value = Integer.MIN_VALUE; // constructor public EditTextNumeric(Context context) { super(context); this.setInputType(InputType.TYPE_CLASS_NUMBER); } // checks whether the limits are set and corrects them if not within limits @Override protected void onTextChanged(CharSequence text, int start, int before, int after) { if (max_value != Integer.MAX_VALUE) { try { if (Integer.parseInt(this.getText().toString()) > max_value) { // change value and keep cursor position int selection = this.getSelectionStart(); this.setText(String.valueOf(max_value)); if (selection >= this.getText().toString().length()) { selection = this.getText().toString().length(); } this.setSelection(selection); } } catch (NumberFormatException exception) { super.onTextChanged(text, start, before, after); } } if (min_value != Integer.MIN_VALUE) { try { if (Integer.parseInt(this.getText().toString()) < min_value) { // change value and keep cursor position int selection = this.getSelectionStart(); this.setText(String.valueOf(min_value)); if (selection >= this.getText().toString().length()) { selection = this.getText().toString().length(); } this.setSelection(selection); } } catch (NumberFormatException exception) { super.onTextChanged(text, start, before, after); } } super.onTextChanged(text, start, before, after); } // set the max number of digits the user can enter public void setMaxLength(int length) { InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(length); this.setFilters(FilterArray); } // set the maximum integer value the user can enter. // if exeeded, input value will become equal to the set limit public void setMaxValue(int value) { max_value = value; } // set the minimum integer value the user can enter. // if entered value is inferior, input value will become equal to the set limit public void setMinValue(int value) { min_value = value; } // returns integer value or 0 if errorous value public int getValue() { try { return Integer.parseInt(this.getText().toString()); } catch (NumberFormatException exception) { return 0; } } }
Ejemplo de uso:
final EditTextNumeric input = new EditTextNumeric(this); input.setMaxLength(5); input.setMaxValue(total_pages); input.setMinValue(1);
Todos los otros métodos y atributos que se aplican a EditText
, por supuesto, también funcionan.
Debido a la observación de goto10, reuní el siguiente código para protegerse contra perder otros filtros con la configuración de la longitud máxima:
/** * This sets the maximum length in characters of an EditText view. Since the * max length must be done with a filter, this method gets the current * filters. If there is already a length filter in the view, it will replace * it, otherwise, it will add the max length filter preserving the other * * @param view * @param length */ public static void setMaxLength(EditText view, int length) { InputFilter curFilters[]; InputFilter.LengthFilter lengthFilter; int idx; lengthFilter = new InputFilter.LengthFilter(length); curFilters = view.getFilters(); if (curFilters != null) { for (idx = 0; idx < curFilters.length; idx++) { if (curFilters[idx] instanceof InputFilter.LengthFilter) { curFilters[idx] = lengthFilter; return; } } // since the length filter was not part of the list, but // there are filters, then add the length filter InputFilter newFilters[] = new InputFilter[curFilters.length + 1]; System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length); newFilters[curFilters.length] = lengthFilter; view.setFilters(newFilters); } else { view.setFilters(new InputFilter[] { lengthFilter }); } }
Otra manera en el archivo xml.
<EditText android:id="@+id/input" android:layout_width="0dip" android:layout_height="wrap_content" android:inputType="number" android:maxLength="6" android:hint="@string/hint_gov" android:layout_weight="1" />
<EditText android:id="@+id/input" android:layout_width="0dip" android:layout_height="wrap_content" android:inputType="number" android:maxLength="6" android:hint="@string/hint_gov" android:layout_weight="1" />
android:maxLength="6"
limita la longitud del EditText
a 6 caracteres.
Esta es una clase EditText personalizada que permite que el filtro Length permanezca junto con otros filtros. Gracias a la respuesta de Tim Gallagher (abajo)
import android.content.Context; import android.text.InputFilter; import android.util.AttributeSet; import android.widget.EditText; public class EditTextMultiFiltering extends EditText{ public EditTextMultiFiltering(Context context) { super(context); } public EditTextMultiFiltering(Context context, AttributeSet attrs) { super(context, attrs); } public EditTextMultiFiltering(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setMaxLength(int length) { InputFilter curFilters[]; InputFilter.LengthFilter lengthFilter; int idx; lengthFilter = new InputFilter.LengthFilter(length); curFilters = this.getFilters(); if (curFilters != null) { for (idx = 0; idx < curFilters.length; idx++) { if (curFilters[idx] instanceof InputFilter.LengthFilter) { curFilters[idx] = lengthFilter; return; } } // since the length filter was not part of the list, but // there are filters, then add the length filter InputFilter newFilters[] = new InputFilter[curFilters.length + 1]; System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length); newFilters[curFilters.length] = lengthFilter; this.setFilters(newFilters); } else { this.setFilters(new InputFilter[] { lengthFilter }); } } }
Podemos establecer directamente en xml:
android:maxLength="10"
En el archivo XML agregue el atributo: –
android:maxLength="10"
- Android Studio es lento (cómo acelerar)?
- Tarea de fondo, diálogo de progreso, cambio de orientación – ¿hay alguna solución de trabajo 100%?