Format credit card in edit text in android

后端 未结 29 2099
耶瑟儿~
耶瑟儿~ 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 19:49

    In your layout:

        
    

    Here the TextWachter which sets a space on every 4 digits in a 16 number credit card.

    class CreditCardFormatWatcher : TextWatcherAdapter() {
    
        override fun afterTextChanged(s: Editable?) {
            if (s == null || s.isEmpty()) return
    
            s.forEachIndexed { index, c ->
                val spaceIndex = index == 4 || index == 9 || index == 14
                when {
                    !spaceIndex && !c.isDigit()     -> s.delete(index, index + 1)
                    spaceIndex && !c.isWhitespace() -> s.insert(index, " ")
                }
            }
    
            if (s.last().isWhitespace())
                s.delete(s.length - 1, s.length)
        }
    
    }
    

提交回复
热议问题