Daniel
Daniel

Reputation: 1072

AfterTextChanged called even after removing the listener

I have some code in onItemSelect which modifies an EditText but before doing that I remove its TextWatcher. Regardless of that immediately after I modify the EditText the afterTextChanged method is called. My method is something like this:

   public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
      switch (adapterView.getId()) {
          case R.id.someId:
            // Remove the listener 
            // make changes to the EditText
            // add the listener 

            break;
      }
  }

How can I really remove the listener? If I don't remove it the thing just calls itself more times.

Upvotes: 1

Views: 921

Answers (1)

Lars Blumberg
Lars Blumberg

Reputation: 21371

The solution is to notify your TextWatcher that you are going to modify the text programmatically. Set this flag (call it enabled) before editing the text (instead of removing the listener) and reset it when modification is done. Within your TextWatcher you check if this flag is set and if so ignore any changes.

class MyTextWatcher extends TextWatcher {

    boolean mIsEnabled = true;

    public void setEnabled(boolean enabled) {
        mIsEnabled = enabled;
    }

    @Override
    protected afterTextChanged(Editable s) {
        if (!enabled) return;
        ...
    }

    ...
} 

Upvotes: 2

Related Questions