Search code examples
androidtextwatchertextchangedaddtextchangedlistener

TextWatcher event is fired multiple times


I had a strange error occuring with TextWatcher firing multiple times with different inputs on a single change of text, mainly on entering or removing spaces.

After some investigation I got following results on "afterTextChanged":
Test 1, enter space in String "Suger" -> "Su gar":

  1. "gar"
  2. " "
  3. "Su"
  4. "Su gar"

Test 2, enter another space in String "Su gar" -> "Su ga r":

  1. "Su r"
  2. "Su "
  3. "Su ga "
  4. "Su ga r"

I've already found a related question suggesting to shut down text suggestions (which I want to keep) or just take the first call (which is plain wrong in my tests): TextWatcher events are being fired multiple times

Theoretically I could just take every event and update everytime because the last one is correct, but I really don't want 3-4 updates in my viewmodel, when one should do the trick.

Has anyone encountered this problem too and has a viable solution?

If needed I can add some code, but I'm really just using the default implementation of a Textwatcher set to an EditText.


Solution

  • For the record, any other people who might run into the same issue:

    I've just sat down with new energy for this topic and managed to solve it without using a debouncer or deactivating my autocomplete functionby removing the textwatcher completely.

    Instead I used a focusListener like this:

       int pos = this.getAbsoluteAdapterPosition();
        et_text.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                updateText(pos, et_text.getText().toString());
            }
        });
    

    With that in place, I do only get the final result of the text entered by a user, without any events triggered in between. There still is a slight issue currently, since the User can enter something and then press my save-Button and his input is lost (due to focus not having changed), but that's a minor issue and I'm sure there's help for that, too.