-1

To remove empty spaces of a String at the beginning and at the end, we can use the trim method. The problem is, the TextInputLayout's counter still counts these empty fields. As you can see in the screenshot, it takes my input as valid because it is only 2 trimmed characters (which is not over the maximum of 15), but it the counter itself still shows it as going over the allowed limit, because it counts the empty spaces as well. Is there an easy way to fix this?

enter image description here

Florian Walther
  • 6,237
  • 5
  • 46
  • 104

1 Answers1

0

You need to create a custom InputFilter for that I think:

InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (Character.isSpaceChar(source.charAt(i))) {
                return "";
            }
        }
        return null;
    }
};
edit.setFilters(new InputFilter[] { filter });

Note that this filter would delete all spaces, so you need extra logic to just delete the ones before and after the text

see: How do I use InputFilter to limit characters in an EditText in Android?

julienduchow
  • 1,026
  • 1
  • 11
  • 29