More elegant way would be using a regular expression ( regex ) as follows:
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\.)?");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
To use it do:
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…