How to make EditText accept input in format:
4digit 4digit 4digit 4digit
I tried Custom format edit text input android to acc
I just created a Kotlin class based on Chris Jenkins's answer, and it is usable for this special condition of credit cart input and other related situations. You need to specify the character and digit count for this TextWahcher.
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
/**
* Formats the watched EditText for digits values
*/
class DigitFormatWatcher(private val space: Char, private val characterCount: Int) :
TextWatcher {
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) {
// Remove spacing char
if (s.isNotEmpty() && s.length % (characterCount - 1) == 0) {
val c = s[s.length - 1]
if (space == c) {
s.delete(s.length - 1, s.length)
}
}
// Insert char where needed.
if (s.isNotEmpty() && s.length % (characterCount - 1) == 0) {
val c = s[s.length - 1]
// Only if its a digit where there should be a space we insert a space
if (Character.isDigit(c) && TextUtils.split(
s.toString(),
space.toString()
).size <= (characterCount + 1)
) {
s.insert(s.length - 1, space.toString())
}
}
}
}