金额输入控制代码

每个人的实现思路不一样,写起来费劲这里做个笔记。
金额输入控制代码_第1张图片

 
moneyEd.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(tv: Editable?) {
                var toString = tv.toString()
                if (toString.isNotEmpty()) {
                    moneyEd.removeTextChangedListener(this)
                    val split = toString.split(".")
                    val size = split.size
                    if ("." == toString) toString = "0."
                    var substring = when (size) {
                        1 -> toString
                        2 -> if (split[1].length > 2) toString.substring(0,toString.indexOf(".")+3) else toString
                        3 -> toString.substring(0, toString.lastIndexOf("."))
                        else -> toString.substring(0, toString.indexOf("."))
                    }

                    if (substring.toDouble() > comeMoney.toDouble()) substring = comeMoney
                    moneyEd.setText(substring)
                    moneyEd.setSelection(substring.length)
                    moneyEd.addTextChangedListener(this)
                }
            }

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

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

当然用下面这个正则实现更简单

 "".matches("(^[1-9]([0-9]+)?(\\.[0-9]{1,2})?\$)|(^(0){1}\$)|(^[0-9]\\.[0-9]([0-9])?\$)".toRegex())

 var regStrs = [
		['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上,但首位为0
		['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
		['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
		['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
	]

你可能感兴趣的:(koltin)