Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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