安卓开发

安卓通过InputFilter限制EditText输入

2020-12-01  本文已影响0人  蓝不蓝编程

目标

限制EditText输入,最多允许三位小数,最大1000000.

解决方案

private fun editTextFilter(context: Context): InputFilter {
        //最大允许输入的数
        val maxValue = 1000000

        //最多保留几位小数
        val maxCountAfterDot = 3
        
        return object : InputFilter {
            override fun filter(source: CharSequence, start: Int, end: Int,
                                dest: Spanned, dstart: Int, dend: Int): CharSequence? {
                val currentInput = source.toString()
                val originalText = etcFeeEt.text
                if (originalText.isNotEmpty()) {
                    val dotIndex = originalText.indexOf(".")
                    if (dotIndex != -1 && dotIndex < originalText.length - maxCountAfterDot) {
                        return ""
                    }
                    val tempText = "$originalText$currentInput"
                    val doubleValue = tempText.toDoubleOrNull()
                    if (doubleValue == null) {
                        return ""
                    } else if (doubleValue > maxValue) {
                        Toast.makeText(context, "数字太大", Toast.LENGTH_LONG).show()
                        return ""
                    }
                } else {
                    if (currentInput == ".") {
                        return ""
                    }
                }
                return source
            }
        }
    }
editText.filters = arrayOf(editTextFilter(context))
上一篇下一篇

猜你喜欢

热点阅读