目标
限制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))
网友评论