输入掩码(红色疯狂机器人)以合法方式删除空格

时间:2018-12-18 14:37:57

标签: android input-mask

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

例如:

“ 4444_4444_4”

“ 444_4444 _”

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

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

1 个答案:

答案 0 :(得分:0)

尝试一下。希望它会有所帮助。 (科特琳的例子)

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)

        }

    }


}