Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save albodelu/4b2a3822b8f1972e931d01c246558cfa to your computer and use it in GitHub Desktop.
Save albodelu/4b2a3822b8f1972e931d01c246558cfa to your computer and use it in GitHub Desktop.
Android EditText TextWatcher for formatting credit card number made with Kotlin
class CreditCardNumberFormattingTextWatcher : TextWatcher {
private var current = ""
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable) {
if (s.toString() != current) {
val userInput = s.toString().replace("[^\\d]".toRegex(), "")
if (userInput.length <= 16) {
val sb = StringBuilder()
for (i in 0..userInput.length - 1) {
if (i % 4 == 0 && i > 0) {
sb.append(" ")
}
sb.append(userInput[i])
}
current = sb.toString()
s.filters = arrayOfNulls<InputFilter>(0)
}
s.replace(0, s.length, current, 0, current.length)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment