Created
January 23, 2021 17:59
-
-
Save timrijckaert/3fc8da852a8360abb8b987273de126a3 to your computer and use it in GitHub Desktop.
Inserts spaces after every block of 4 digits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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