Search code examples
androidandroid-edittextaddtextchangedlistener

Edittext remove textchangedlistener


I've been looking for answers on how i can remove my text change listener.

here is my current code:

 public void enableTextChangedListener(boolean enableFormatting){
        if (enableFormatting) {
            if (!"1".equals(mAmountEditText.getTag())) {
                mAmountEditText.addTextChangedListener(new StringUtils.NumberTextWatcherForThousand(mAmountEditText));
                mAmountEditText.setTag("1");

  }
        }
        else {
            mAmountEditText.removeTextChangedListener(new StringUtils.NumberTextWatcherForThousand(mAmountEditText));
        }
    }

When my boolean enableFormatting is False, the textchangelistener is still there.

i can provide the class NumberTextwatcherForThousands if you want for more clearer explanation of my code.


Solution

  • You need to keep a reference to the listener, right now you are creating a new listener when you are trying to remove the old one. Something like this:

    textWatcher = new StringUtils.NumberTextWatcherForThousand(mAmountEditText);
    public void enableTextChangedListener(boolean enableFormatting){
        if (enableFormatting) {
            if (!"1".equals(mAmountEditText.getTag())) {
                mAmountEditText.addTextChangedListener(textWatcher);
                mAmountEditText.setTag("1");
    
    }
        }
        else {
            mAmountEditText.removeTextChangedListener(textWatcher);
        }
    }