首页 > 解决方案 > 输入掩码(红色疯狂机器人)自动删除空格

问题描述

我想以[0000] [0000] [0000] [0000]等格式为edittext创建信用卡掩码掩码,但用户不应该手动删除空格

例如:

“4444_4444_4”

“444_4444_”

如何实现自动删除空格“”?

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

标签: androidinput-mask

解决方案


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)

        }

    }


}

推荐阅读