Skip to content

Instantly share code, notes, and snippets.

@Anrimian
Last active December 3, 2020 10:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anrimian/168f3ed6b12df7d7da6230f418171dbd to your computer and use it in GitHub Desktop.
Save Anrimian/168f3ed6b12df7d7da6230f418171dbd to your computer and use it in GitHub Desktop.

Improved solution from so answer, with copy-paste support

Credit card input filter example:

yourEditText.setFilters(new InputFilter[]{
            new InputFilter.LengthFilter(23),
            new SpacesInputFilter(23, new int[]{4, 9, 14, 19}, ' '),
});
import android.text.InputFilter;
import android.text.Spanned;
public class SpacesInputFilter implements InputFilter {
private final int max;
private final int[] spaces;
private final char space;
public SpacesInputFilter(int max, int[] spaces, char space) {
this.max = max;
this.spaces = spaces;
this.space = space;
}
public CharSequence filter(CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {
if (dest != null && dest.toString().trim().length() > max) {
return null;
}
if (source.length() == 1 && contains(dstart, spaces) && source.charAt(0) != space) {
return space + source.toString();
}
//copy-paste case
int spacesCount = 0;
if (start == 0 && source.length() == end) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
char symbol = source.charAt(i);
if (contains(i + spacesCount, spaces) && symbol != space) {
spacesCount++;
sb.append(space);
}
sb.append(symbol);
}
return sb.toString();
}
//unhandled: partial copy-paste
return null; // keep original
}
private boolean contains(int i, int[] array) {
for (int j: array) {
if (j == i) {
return true;
}
}
return false;
}
}
@ChrisWoodard
Copy link

Really liking your class, very handy. One improvement though would be to NOT allow the space character in positions other than those specified in the spaces Array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment