public class DecimalDigitsFilter implements InputFilter {
private int maxDigits;
private SpannableStringBuilder spannableStringBuilder;
DecimalDigitsFilter(int maxDigits) {
this.maxDigits = maxDigits;
spannableStringBuilder = new SpannableStringBuilder();
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
spannableStringBuilder.clear();
spannableStringBuilder.append(dest.toString());
spannableStringBuilder.insert(dstart, source.toString());
String numValue = spannableStringBuilder.toString();
if (!numValue.contains(".")) return null;
int dotIndex = numValue.indexOf(".") + 1;
int digits = numValue.substring(dotIndex).length();
if (digits > maxDigits) {
return "";
}
return source;
}
}
网友评论