¿Cómo usar la clase TextWatcher en Android?

¿Puede alguien decirme cómo enmascarar la subcadena en EditText o cómo cambiar la entrada de subcadena EditText a tipo de contraseña o reemplazar por otro carácter como este 123xxxxxxxxx3455

String contents = et1.getText().toString(); et1.setText(contents.replace.substring(0, contents.length()-2),"*"); 

Por favor, dime cómo puedo usar el método TextWatcher en Android.

Editar: No soy el contestador original. No tengo ni idea de cómo este post consiguió tantos upvotes cuando no explica nada. He guardado el contenido original abajo, pero por favor vea esta respuesta para una explicación mucho más completa de cada método y ejemplos.

¿Puede por favor revisar la pregunta? Qué se ha pedido? ¿Esta respuesta da suficiente información para la pregunta? La respuesta que está en el enlace dado es demasiada información. Es adecuado para la pregunta como. ¿Qué es textwatcher y cómo funciona? ¿Cuáles son los detalles internos sobre él? Supongo que esa es la razón por la que hay muchos upvotes. Responder sólo lo que se le pide? Demasiado sal ruinas la comida.


Para el uso de TextWatcher ..

 et1.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); 

La interfaz de TextWatcher tiene 3 métodos callbacks que se llaman en el orden siguiente cuando se produjo un cambio en el texto:

1 beforeTextChanged(CharSequence s, int start, int count, int after)

: Se llama antes de que se hayan aplicado los cambios al texto.
El parámetro s es el texto antes de que se aplique cualquier cambio.
El parámetro de start es la posición del beguinage de la parte cambiada en el texto.
El parámetro count es la longitud de la parte modificada en la secuencia s desde la posición start .
Y el parametter after es la longitud de la nueva secuencia que reemplazará la parte de la secuencia s de start a start+count .
No debe cambiar el texto en el TextView de este método (utilizando myTextView.setText(String newText) ).

2 onTextChanged(CharSequence s, int start, int before, int count)

Similar al método beforeTextChanged pero llamado después de que el texto cambia.
El parámetro s es el texto después de que se han aplicado los cambios.
El parámetro de start es el mismo que en el método beforeTextChanged .
El parámetro de count es el parámetro after del método beforeTextChanged.
Y el parámetro before es el parámetro de count en el método beforeTextChanged.
No debe cambiar el texto en el TextView de este método (utilizando myTextView.setText(String newText) ).

3 afterTextChanged(Editable s)

Puede cambiar el texto en el TextView de este método.
/! \ Warning: Cuando cambia el texto en TextView , el TextWatcher se disparará de nuevo, iniciando un bucle infinito. A continuación, agregue como una propiedad boolean _ignore que impida el bucle infinito.
Ejemplo:

 new TextWatcher() { boolean _ignore = false; // indicates if the change was made by the TextWatcher itself. @Override public void afterTextChanged(Editable s) { if (_ignore) return; _ignore = true; // prevent infinite loop // Change your text here. // myTextView.setText(myNewText); _ignore = false; // release, so the TextWatcher start to listen again. } // Other methods... } 

Resumen:

Introduzca aquí la descripción de la imagen

Mi oyente personalizado:

Personalmente, hice mi escucha de texto personalizado, que me da las 4 partes de los textos en cadenas por separado, que es mucho más intuitivo de usar creo.

  /** * Text view listener which splits the update text event in four parts: * <ul> * <li>The text placed <b>before</b> the updated part.</li> * <li>The <b>old</b> text in the updated part.</li> * <li>The <b>new</b> text in the updated part.</li> * <li>The text placed <b>after</b> the updated part.</li> * </ul> * Created by Jeremy B. */ public abstract class TextViewListener implements TextWatcher { /** * Unchanged sequence which is placed before the updated sequence. */ private String _before; /** * Updated sequence before the update. */ private String _old; /** * Updated sequence after the update. */ private String _new; /** * Unchanged sequence which is placed after the updated sequence. */ private String _after; /** * Indicates when changes are made from within the listener, should be ommitted. */ private boolean _ignore = false; @Override public void beforeTextChanged(CharSequence sequence, int start, int count, int after) { _before = sequence.subSequence(0,start).toString(); _old = sequence.subSequence(start, start+count).toString(); _after = sequence.subSequence(start+count, sequence.length()).toString(); } @Override public void onTextChanged(CharSequence sequence, int start, int before, int count) { _new = sequence.subSequence(start, start+count).toString(); } @Override public void afterTextChanged(Editable sequence) { if (_ignore) return; onTextChanged(_before, _old, _new, _after); } /** * Triggered method when the text in the text view has changed. * <br/> * You can apply changes to the text view from this method * with the condition to call {@link #startUpdates()} before any update, * and to call {@link #endUpdates()} after them. * * @param before Unchanged part of the text placed before the updated part. * @param old Old updated part of the text. * @param aNew New updated part of the text? * @param after Unchanged part of the text placed after the updated part. */ protected abstract void onTextChanged(String before, String old, String aNew, String after); /** * Call this method when you start to update the text view, so it stops listening to it and then prevent an infinite loop. * @see #endUpdates() */ protected void startUpdates(){ _ignore = true; } /** * Call this method when you finished to update the text view in order to restart to listen to it. * @see #startUpdates() */ protected void endUpdates(){ _ignore = false; } } 

Ejemplo de uso:

 myEditText.addTextChangedListener(new TextViewListener() { @Override protected void onTextChanged(String before, String old, String aNew, String after) { // intuitive usation of parametters String completeOldText = before + old + after; String completeNewText = before + aNew + after; // update TextView startUpdates(); // to prevent infinite loop. myEditText.setText(myNewText); endUpdates(); } 

Uso de TextWatcher en Android

Aquí hay un código de ejemplo. Pruebe a utilizar el método addTextChangedListener de TextView

 addTextChangedListener(new TextWatcher() { BigDecimal previousValue; BigDecimal currentValue; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (isFirstTimeChange) { return; } if (s.toString().length() > 0) { try { currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.')); } catch (Exception e) { currentValue = new BigDecimal(0); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (isFirstTimeChange) { return; } if (s.toString().length() > 0) { try { previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.')); } catch (Exception e) { previousValue = new BigDecimal(0); } } } @Override public void afterTextChanged(Editable editable) { if (isFirstTimeChange) { isFirstTimeChange = false; return; } if (currentValue != null && previousValue != null) { if ((currentValue.compareTo(previousValue) > 0)) { //setBackgroundResource(R.color.devises_overview_color_green); setBackgroundColor(flashOnColor); } else if ((currentValue.compareTo(previousValue) < 0)) { //setBackgroundResource(R.color.devises_overview_color_red); setBackgroundColor(flashOffColor); } else { //setBackgroundColor(textColor); } handler.removeCallbacks(runnable); handler.postDelayed(runnable, 1000); } } }); 

Una perspectiva un poco más grande de la solución:

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.yourlayout, container, false); View tv = v.findViewById(R.id.et1); ((TextView) tv).addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { SpannableString contentText = new SpannableString(((TextView) tv).getText()); String contents = Html.toHtml(contentText).toString(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); return v; } 

Esto funciona para mí, hacerlo por primera vez.

Crear subclase personalizada de TextWatcher:

 public class CustomWatcher implements TextWatcher { private boolean mWasEdited = false; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mWasEdited){ mWasEdited = false; return; } // get entered value (if required) String enteredValue = s.toString(); String newValue = "new value"; // don't get trap into infinite loop mWasEdited = true; // just replace entered value with whatever you want s.replace(0, s.length(), newValue); } } 

Establecer listener para su EditText:

 mTargetEditText.addTextChangedListener(new CustomWatcher()); 
  public class Test extends AppCompatActivity { EditText firstEditText; EditText secondEditText; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); firstEditText = (EditText)findViewById(R.id.firstEditText); secondEditText = (EditText)findViewById(R.id.secondEditText); firstEditText.addTextChangedListener(new EditTextListener()); } private class EditTextListener implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { secondEditText.setText(firstEditText.getText()); } @Override public void afterTextChanged(Editable s) { } } } 
 editext1.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { editext2.setText(new String(s.toString())); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { editext2.setText(new String(s.toString())); } @Override public void afterTextChanged(Editable s) { editext2.setText(new String(s.toString())); } }); 

Para más información, haga clic aquí http://androiddhina.blogspot.in/2015/05/android-textwatcher.html

  • Cómo eliminar todos los oyentes agregados con addTextChangedListener
  • Cómo limitar el texto en números sólo de 0-59 en Editar texto en Android?
  • Eventos de TextWatcher se están llamando dos veces
  • ¿Cómo mostrar "No Result" en ListView filtrable?
  • Necesita ayuda para que un TextWatcher de Android funcione con datos de código de barras compuesto entrantes
  • Los caracteres de cuenta con TextWatcher fallan en HTC longpress
  • ¿Cómo utilizar Single TextWatcher para múltiples EditTexts?
  • Cómo aplicar el evento de cambio de texto en EditText
  • Cómo sólo permitir números positivos en un EditText
  • No se puede insertar en Editable
  • Espaciado de letras en EditText para Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.