I have a requirement to constrain an EditText
to never have adjacent space characters. It's easy enough to write an InputFilter
to prevent the input of a space character adjacent to another one, but I'm stuck trying to figure out a clean way to handle deletions/replacements. For an example of where an InputFilter
fails, consider the sequence (where I'm using • as a visual representation of a space):
sit•a•bit
If the user deletes the word "a", the result will be:
sit••bit
which violates the constraint. Nothing I can do in an InputFilter
will help, since it is only allowed to modify the replacement string and, in the case of deletions, the replacement string is zero length. (In this case, I would like to automatically delete one of the spaces when the user deletes the "a".)
The only thing I can think to do is to add a TextWatcher
and further modify the contents of the EditText
in afterTextChanged()
. But whether I do this in place of or in addition to using an InputFilter
, this strikes me as a convoluted and not very efficient way to handle the problem.
Is there any better way to deal with this?
NOTE (In response to a couple of the comments and posted answers) I just want to be clear that I don't need suggestions about how to replace two space characters with one; that's quite straightforward. The question concerns the inefficient nature of changing the contents of an EditText
from within TextWatcher#afterTextChanged()
. At a minimum, making such a change always triggers a recursive call to afterTextChanged()
where I have to do additional processing to ensure that the recursion doesn't repeat.
What I'm frustrated about is that I can get most of what I need very efficiently with an InputFilter
but to finish the job, I need to basically throw out that approach and go with an (apparently) inefficient TextWatcher
.