Last active
November 30, 2023 14:03
-
-
Save hleinone/5b445e5475ca9f8a3bdc6a44998f4edd to your computer and use it in GitHub Desktop.
Android EditText TextWatcher for formatting credit card number made with Kotlin
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 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(nonDigits,"") | |
if (userInput.length <= 16) { | |
current = userInput.chunked(4).joinToString(" ") | |
s.filters = arrayOfNulls<InputFilter>(0) | |
} | |
s.replace(0, s.length, current, 0, current.length) | |
} | |
} | |
companion object { | |
private val nonDigits = Regex("[^\\d]") | |
} | |
} |
how this code does't go into infinite loop? i think the answer is in
s.filters = arrayOfNulls<InputFilter>(0)
but i cannot figure out
if (s.toString() != current)
will prevent that.
Work like charm, Thanks man!
You saved my day, Thanks man!
@mohsenmdb Cheers, my pleasure!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how this code does't go into infinite loop? i think the answer is in
s.filters = arrayOfNulls<InputFilter>(0)
but i cannot figure out