public class DecimalDigitsUtil implements InputFilter {
private int decimalDigits = 0;
public DecimalDigitsUtil(int decimalDigits) {
this.decimalDigits = decimalDigits;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if ("".equals(source.toString())) {
return null;
}
String value = dest.toString();
String[] splitArray = value.split("\\.");
if (splitArray.length > 1) {
String dotValue = splitArray[1];
int diff = dotValue.length() + 1 - decimalDigits;
if (diff > 0) {
return source.subSequence(start, end - diff);
}
}
return null;
}
}
调用:把EditText的小数位数限定为4位
etTest3.setFilters(new InputFilter[]{new DecimalDigitsUtil(4)});