Skip to content

Instantly share code, notes, and snippets.

@timrijckaert
Created January 23, 2021 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timrijckaert/3fc8da852a8360abb8b987273de126a3 to your computer and use it in GitHub Desktop.
Save timrijckaert/3fc8da852a8360abb8b987273de126a3 to your computer and use it in GitHub Desktop.
Inserts spaces after every block of 4 digits
class CreditCardTextWatcher(private val maxLength: Int) : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
val textLength = s.length
// first remove any previous span
val spans = s.getSpans(0, s.length, SpaceSpan::class.java)
for (i in spans.indices) {
s.removeSpan(spans[i])
}
// then truncate to max length
if (maxLength > 0 && textLength > maxLength - 1) {
s.replace(maxLength, textLength, "")
}
// finally add margin spans
for (i in 1..(textLength - 1) / 4) {
val end = i * 4
val start = end - 1
val marginSPan = SpaceSpan()
s.setSpan(marginSPan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
public class SpaceSpan extends ReplacementSpan {
private static final String SPACE = " ";
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
float padding = paint.measureText(SPACE, 0, 1);
float textSize = paint.measureText(text, start, end);
return (int) (padding + textSize);
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y,
int bottom, @NonNull Paint paint) {
canvas.drawText(text.subSequence(start, end) + SPACE, x, y, paint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment