EditText 小数 长度限制
2018-10-29 本文已影响5人
詹徐照
定义filter
public class DecimalInputFilter implements InputFilter {
private final int mDecimalLength;
public DecimalInputFilter(int decimalLength) {
if (decimalLength < 0) {
throw new IllegalArgumentException("decimalLength must >= 0");
}
mDecimalLength = decimalLength;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String sourceString = source.toString();
if (TextUtils.isEmpty(sourceString)) {
return sourceString;
}
CharSequence result = source;
String destString = dest.toString();
if (destString.contains(".")) {
int dotIndex = destString.indexOf(".");
if (dstart > dotIndex) { // 新输入的内容在小数部分
int availableDecimalLength = dotIndex + mDecimalLength + 1 - dest.length();
if (availableDecimalLength > 0) {
result = source.subSequence(start, start + availableDecimalLength);
} else {
result = "";
}
}
}
return result;
}
}
使用filter
editText.setFilters(new InputFilter[]{new DecimalInputFilter(2)});