-1

I want to create mask for credit card mask for edittext in format like [0000] [0000] [0000] [0000], but not user should delete whitespaces manually

For example:

"4444_4444_4"

"444_4444_"

How to implement deleting of whitespace " " automatically?

https://github.com/RedMadRobot/input-mask-android

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Strangelove
  • 761
  • 1
  • 7
  • 29

1 Answers1

0

Try this. Hope it will help. (Kotlin example)

class CreditCardFormattingTextWatcher : TextWatcher {

    private var etCard: EditText? = null
    private var isDelete: Boolean = false


    constructor(etcard: EditText) {
        this.etCard = etcard
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        isDelete = before != 0
    }

    override fun afterTextChanged(s: Editable) {
        val source = s.toString()
        val length = source.length

        val stringBuilder = StringBuilder()
        stringBuilder.append(source)

        if (length > 0 && length % 5 == 0) {
            if (isDelete)
                stringBuilder.deleteCharAt(length - 1)
            else
                stringBuilder.insert(length - 1, " ")
            etCard?.setText(stringBuilder)
            etCard?.setSelection(etCard?.text?.length ?: 0)

        }

    }


}
ArbenMaloku
  • 548
  • 4
  • 15