Skip to content

Instantly share code, notes, and snippets.

@masoudkarimi
Created October 12, 2021 18:05
Show Gist options
  • Save masoudkarimi/16395b6597107980eaecabf94233cbda to your computer and use it in GitHub Desktop.
Save masoudkarimi/16395b6597107980eaecabf94233cbda to your computer and use it in GitHub Desktop.
Masked Input EditText
etCardNumber.doAfterTextChanged { editable ->
if (editable == null) return
val paddingPx = etCardNumber.paint.measureText("X").toInt()
formatDebitCard(editable, paddingPx)
}
private fun formatDebitCard(editable: Editable, paddingPx: Int) {
val textLength = editable.length
// first remove any previous span
val spans = editable.getSpans(
0, editable.length,
PaddingRightSpan::class.java
)
for (i in spans.indices) {
editable.removeSpan(spans[i])
}
// adding spans
for (i in 0 until textLength) {
// 000`0` 000`0` 000`0` 0000
if (i in arrayOf(3, 7, 11)) {
val marginSPan =
PaddingRightSpan(paddingPx)
editable.setSpan(marginSPan, i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
class PaddingRightSpan(private val mPadding: Int) : ReplacementSpan() {
override fun getSize(
paint: Paint, text: CharSequence,
start: Int, end: Int,
fm: Paint.FontMetricsInt?
): Int {
val widths = FloatArray(end - start)
paint.getTextWidths(text, start, end, widths)
var sum = 0
for (i in widths.indices) {
sum += widths[i].toInt()
}
return sum + mPadding
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
canvas.drawText(text, start, end, x, y.toFloat(), paint)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment