1

So I am currently working on an application which takes the user input, fires a backspace to delete the input, and then adds some other text. (So yes I am basically overriding their input using a TextWatcher)

No the problem: when I call text.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));, it will fire onTextChanged again and again. Now is there any way to delete the user input without firing the onTextChanged again?

Thanks!

1
  • Have you tried setting the text directly? Something like textView.setText(text.substring(0, length - 1)). Commented Feb 24, 2015 at 20:26

3 Answers 3

1

Don't dispatch key events from inside the onTextChanged callback. You can keep an internal buffer with the text and set the entire TextView to that buffer on every interesting key event.

Sign up to request clarification or add additional context in comments.

Comments

1

I fixed it by calling edittext.removeTextChangedListener(this);, then dispatching the key and then calling edittext.addTextChangedListener(this); again. is this a clean way too? happy to hear your opinions.

Comments

0

Probably, you are trying to further change the text the user just changed using a TextWatcher. To be able to do that, your best option is to use afterTextChanged method:

public abstract void afterTextChanged (Editable s) 

This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.

To avoid recursion, you can set a flag indicating you are the one changing the text, and clear the flag in the next call. You can also use the other callbacks (beforeTextChanged and onTextChanged) to gather more information about the change.

Reference: http://developer.android.com/reference/android/text/TextWatcher.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.