Format credit card in edit text in android

后端 未结 29 2055
耶瑟儿~
耶瑟儿~ 2020-11-30 19:18

How to make EditText accept input in format:

4digit 4digit 4digit 4digit 

I tried Custom format edit text input android to acc

29条回答
  •  旧时难觅i
    2020-11-30 19:49

    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())
                }
            }
        }
    }
    

提交回复
热议问题