Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear EditText text after adding onTextChanged implemenation

I'm adding a listener to an EditText field to appropriately format the number to currency in real time.

        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

        }
    });

However, when I try to clear the EditView field, my App will crash. In addition, the backspace key no longer functions.

like image 297
sonics876 Avatar asked Apr 06 '11 13:04

sonics876


2 Answers

The problem is that your TextWatcher sees that you are "clearing" the text, and therefore sends off a request to its callback methods(afterTextChanged, beforeTextChanged, etc).

What i've done is to simply remove the TextWatcher, clear the text, and add the TextWatcherback to the EditText. That way, nothing is listening to my EditText changes.

You will probably have to hold on to an instance of the TextWatcher instead of inlining it like you did. That way you don't have to create one every time you want to clear the EditText

  1. loanText.removeTextChangedListener(yourTextWatcherObject);
  2. loanText.setText("");
  3. loanText.addTextChangedListener(yourTextWatcherObject);
like image 162
james Avatar answered Oct 18 '22 21:10

james


Try to use afterTextChanged instead. I also had many problems with the other one.

like image 41
2red13 Avatar answered Oct 18 '22 21:10

2red13