一、方案:
@1、addTextChangedListener缺点:保留指定位数后,还是会执行其他附加的TextChangedListener
@2、InputFilter完美解决addTextChangedListener实现的缺点
二、基于InputFilter实现
1、InputFilter 工具类
/** * ggband * 限制 小数和整数的位数 */ public class InputNumLengthFilter implements InputFilter { private int maxPoint; private int maxInteger; public InputNumLengthFilter(int maxPoint, int maxInteger) { this.maxPoint = maxPoint; this.maxInteger = maxInteger; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int maxLength = maxInteger + maxPoint + 1; // 删除等特殊字符,直接返回 if (nullFilter(source)) return null; String dValue = dest.toString(); String[] splitArray = dValue.split("\\.");//在点前后分开两段 if (splitArray.length > 0) { String intValue = splitArray[0]; int errorIndex = dValue.indexOf("."); if (errorIndex == -1) { errorIndex = dValue.length(); } if (intValue.length() >= maxLength - maxPoint - 1 && dstart <= errorIndex) { if (".".equals(source.toString())) { return null; } return ""; } } if (splitArray.length > 1 && dstart == dValue.length()) { String dotValue = splitArray[1]; int diff = dotValue.length() + 1 - maxPoint; if (diff > 0) { try { return source.subSequence(start, end - diff); } catch (IndexOutOfBoundsException e) { return source; } } } if (dest.length() == maxLength - 1 && ".".equals(source.toString())) { return ""; } if (dest.length() >= maxLength) { return ""; } return null; } // 第一个参数是小数部分的位数,第二个参数是总长度(包括小数点) private boolean nullFilter(CharSequence source) { return source.toString().isEmpty(); } }
2、ViewHelper工具类:
/** * 让一个输入框只能输入指定位数小数 和整数位 * * @param editText EditText * @param maxInteger 最大整数位数 * @param maxPoint 最大小数位数 * create by ggband */ public static void setPricePointWithInteger(final EditText editText, final int maxPoint, final int maxInteger, InputFilter... inputFilters) { if (inputFilters == null || inputFilters.length == 0) { editText.setFilters(new InputFilter[]{new InputNumLengthFilter(maxPoint, maxInteger)}); } else { InputFilter[] newInputFilters = new InputFilter[inputFilters.length + 1]; System.arraycopy(inputFilters, 0, newInputFilters, 0, inputFilters.length); newInputFilters[inputFilters.length] = new InputNumLengthFilter(maxPoint, maxInteger); editText.setFilters(newInputFilters); } }
3、使用:
ViewHelper.setPricePointWithInteger(etCpu, 4, 10)
原文地址:https://www.cnblogs.com/ggband/p/11815897.html
时间: 2024-10-27 13:38:53