Borrar texto de EditText después de agregar la implementación onTextChanged

Estoy agregando un oyente a un campo EditText para formatear adecuadamente el número a la moneda en tiempo real.

loanText.addTextChangedListener(new TextWatcher() { private String current = ""; public void onTextChanged(CharSequence s, int start, int before, int count) { if(!s.toString().equals(current)){ String cleanString = s.toString().replaceAll("[$,.]", ""); double parsed = Double.parseDouble(cleanString); String formated = NumberFormat.getCurrencyInstance().format((parsed/100)); current = formated; loanText.setText(formated); loanText.setSelection(formated.length()); } } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } }); 

Sin embargo, cuando intento borrar el campo EditView, mi aplicación se bloqueará. Además, la tecla de retroceso ya no funciona.

El problema es que su TextWatcher ve que está "borrando" el texto y, por lo tanto, envía una solicitud a sus métodos de devolución de llamada ( afterTextChanged , beforeTextChanged , etc.).

Lo que he hecho es simplemente eliminar el TextWatcher , borrar el texto, y agregar el TextWatcher nuevo a la EditText . De esa manera, nada está escuchando mis cambios de EditText .

Es probable que tenga que aferrarse a una instancia de TextWatcher lugar de inlining como lo hizo. De esta manera no tiene que crear uno cada vez que desee borrar el EditText

  1. loanText.removeTextChangedListener(yourTextWatcherObject);
  2. loanText.setText("");
  3. loanText.addTextChangedListener(yourTextWatcherObject);

Intente utilizar afterTextChanged en afterTextChanged lugar. También tuve muchos problemas con el otro.

He encontrado esta clase que funciona muy bien para mí: http://www.java2s.com/Code/Android/UI/ConvertinputvaluetoCurrencyinTextWatcher.htm

Espero que les ahorre tiempo.

 public class MainActivity extends Activity { EditText et; TextWatcher tw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText) findViewById(R.id.et); tw=new 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) { } @Override public void afterTextChanged(Editable s) { et.removeTextChangedListener(tw); et.setText(Math.random()+"");//add your logic here et.addTextChangedListener(tw); }}; et.addTextChangedListener(tw); } 

} Esta es una solución Simple.

Puede comprobar si Texto está vacío en onTextChanged como sigue y no hacer nada si está vacío

s.toString().isEmpty()

 public void onTextChanged(CharSequence s, int start, int before, int count) { if(!s.toString().equals(current) && !s.toString().isEmpty()){ String cleanString = s.toString().replaceAll("[$,.]", ""); double parsed = Double.parseDouble(cleanString); String formated = NumberFormat.getCurrencyInstance().format((parsed/100)); current = formated; loanText.setText(formated); loanText.setSelection(formated.length()); } } 
  • CoordinatorLayout con RecyclerView y EditText
  • Etiqueta flotante Spinner?
  • ¿Cómo mostrar iconos en el menú de desbordamiento de ActionBar?
  • Cambio de enfoque de enfoque de niño android
  • ¿Cómo averiguar qué recurso se utiliza?
  • La mejor manera de Android para hacer que el carrete parezca girar
  • Android - ¿Cómo puedo utilizar el "android: layoutDirection"?
  • Teclado cubre la pantalla en lugar de empujar hasta el diseño?
  • Establecer el diseño propio en la ventana emergente de android
  • Agregar vista a disposición relativa detrás de una vista existente provoca parpadeo de la pantalla
  • actionBarSherlock subtítulo textSize
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.