It is better to use InputFilter interface. Much easier to handle any kind of inputs by using regex. My solution for currency input format:
public class CurrencyFormatInputFilter implements InputFilter {
Pattern mPattern = Pattern.compile("(0|[1-9]+[0-9]*)?(\.[0-9]{0,2})?");
@Override
public CharSequence filter(
CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {
String result =
dest.subSequence(0, dstart)
+ source.toString()
+ dest.subSequence(dend, dest.length());
Matcher matcher = mPattern.matcher(result);
if (!matcher.matches()) return dest.subSequence(dstart, dend);
return null;
}
}
Valid: 0.00, 0.0, 10.00, 111.1
Invalid: 0, 0.000, 111, 10, 010.00, 01.0
How to use:
editText.setFilters(new InputFilter[] {new CurrencyFormatInputFilter()});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…