1、方案:
@一、addTextChangedListener
缺點:保留指定位數後,仍是會執行其餘附加的TextChangedListener
@二、InputFilter
完美解決addTextChangedListener實現的缺點
2、基於InputFilter實現
一、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(); } }
二、ViewHelper工具類:java
/** * 讓一個輸入框只能輸入指定位數小數 和整數位 * * @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); } }
三、使用:
ViewHelper.setPricePointWithInteger(etCpu, 4, 10)