public class PointLengthFilter implements InputFilter {
Pattern mPattern;
public PointLengthFilter(int digitsBeforeZero, int digitsAfterZero) {
String regex = String.format("[0-9]{0,%d}+(\\.[0-9]{0,%d})?", digitsBeforeZero, digitsAfterZero);
mPattern = Pattern.compile(regex);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
//直接输入"."返回"0."
//".x"删除"x"输出为".",inputFilter无法处理成"0.",所以只处理直接输入"."的case
if (".".equals(source.toString()) && "".equals(dest.toString())) {
return "0.";
}
StringBuilder builder = new StringBuilder(dest);
if ("".equals(source)) {
builder.replace(dstart, dend, "");
} else {
builder.insert(dstart, source);
}
String resultTemp = builder.toString();
try{
double result = Double.parseDouble(resultTemp);
if(result>30){
return "";
}
}catch (Exception e){
}
//判断修改后的数字是否满足小数格式,不满足则返回 "",不允许修改
Matcher matcher = mPattern.matcher(resultTemp);
if (!matcher.matches()) {
return "";
}
return null;
}
}