I'm trying to find a way to prevent multiple spaces between words in an EditText and also prevent leading space. I tried to do so with a TextWatcher but I can't figure out how to do it. Any help would be appreciated.
You can do so using an InputFilter. Feel free to use this code snippet:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String stringSource = source.toString();
String stringDest = dest.toString();
if (stringSource.equals(" ")) {
if (stringDest.length() == 0)
return "";
if (stringDest.length() >= 1)
if ((dstart > 0 && txt2.charAt(dstart - 1) == ' ') || (txt2.length() > dstart && txt2.charAt(dstart) == ' ') || dstart == 0)
return "";
}
return null;
}
};
editText.setFilters(new InputFilter[]{filter});
Here is the result on my app:
Hope this helps!