有没有可能拥有一系列的InputFilters,例如只允许输入类似于$1,01
或$100,95
的输入,这是通过以下方式完成的:
editText.filters = arrayOf(CurrencyFormatInputFilter(), InputFilter.LengthFilter(8))
class CurrencyFormatInputFilter : InputFilter {
private val pattern = Pattern.compile(CURRENCY_INPUT_REGEX)
override fun filter(
source: CharSequence,
start: Int,
end: Int,
dest: Spanned,
dstart: Int,
dend: Int
): CharSequence? {
val result = (dest.subSequence(0, dstart).toString()
+ source.toString()
+ dest.subSequence(dend, dest.length))
val matcher = pattern.matcher(result)
return if (!matcher.matches()) dest.subSequence(dstart, dend) else null
}
}