Android - AppCompatEditText 重写,实现 3个文字中间使用空格分离

重写 AppCompatEditText ,实现 以 3 个文字中间使用空格分离

  • 若需要分割符,把空格替换即可
  • 若需要多个文字中间分割的话,把对 3 取余 换下即可。
class AppCompatThreeSpaceEditText : AppCompatEditText {

    var trueText: String = ""
    private var isRun: Boolean = false
    private val threeSpaceEdit = this

    constructor(cxt: Context) : super(cxt) {
        setOnChangeClick()
    }

    constructor(cxt: Context, attributes: AttributeSet) : super(cxt, attributes) {
        setOnChangeClick()
    }

    constructor(cxt: Context, attributes: AttributeSet, defStyleAttr: Int) : super(cxt, attributes, defStyleAttr) {
        setOnChangeClick()
    }

    private fun setOnChangeClick() {
        threeSpaceEdit.addTextChangedListener(object : TextWatcher {
           private var changeBeforeLength: Int = 0

            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                if (s == null) {
                    return
                }
                changeBeforeLength = s.length
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s == null) {
                    return
                }
                if (isRun) {
                    isRun = false
                    return
                }
                isRun = true
                val buffer: java.lang.StringBuffer = java.lang.StringBuffer()
                trueText = s.toString().replace(" ", "")
                if (changeBeforeLength > s.length) {
                    // 删除内容
                    buffer.append(s.toString())
                } else {
                    // 真实输入文字的长度
                    val length = trueText.length
                    for (index in 1..length) {
                        buffer.append(trueText[index - 1])
                        if (index % 3 == 0) {
                            buffer.append(" ")
                        }
                    }
                }

                threeSpaceEdit.setText(buffer.toString())
                threeSpaceEdit.setSelection(buffer.length)
                // LogUtil.v("$trueText")
            }

        })
    }


}

示例:

Android - AppCompatEditText 重写,实现 3个文字中间使用空格分离_第1张图片

你可能感兴趣的:(android,ui)