大家好,,日常开发中,金额一般需要做2位限制,折扣一般做一位小数限制,之前代码里面写了很多onaddTextChangeListener,整个代码看起来非常臃肿,复用性不佳,今天把它抽出一个工具类,希望能对大家有所帮助。
废话不多说,先上工具类,直接复制到你工具类的包即可。
/** * N位小数 * Created by luomingjing on 2017/12/28. */ public class InputNumWatcher implements TextWatcher { public int MAX_LENGTH = 1;//整数数位最大长度 public int MAX_PONIT_LENGTH = 1;//小数位最大长度 EditText editText; String origin; //默认一位 public InputNumWatcher(EditText editText) { this.editText = editText; } /** * MAX_LENGTH位小数输入限制 * * @param MAX_LENGTH */ public InputNumWatcher(EditText editText, int MAX_LENGTH) { if (MAX_LENGTH < 1) { this.MAX_LENGTH = 1; } else { this.MAX_LENGTH = MAX_LENGTH; } this.editText = editText; } public InputNumWatcher(EditText editText, int MAX_LENGTH, int MAX_PONIT_LENGTH) { if (MAX_LENGTH < 1) { this.MAX_LENGTH = 1; } else { this.MAX_LENGTH = MAX_LENGTH; } if (MAX_LENGTH < 1) { this.MAX_PONIT_LENGTH = 1; } else { this.MAX_PONIT_LENGTH = MAX_PONIT_LENGTH; } this.editText = editText; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { origin = s.toString().trim(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String trim = s.toString().trim(); if (!TextUtils.isEmpty(trim)) { if (trim.startsWith(".")&&trim.length()<=MAX_PONIT_LENGTH + 1){ editText.setText(0+trim); try { String trim1 = editText.getText().toString().trim(); editText.setSelection(trim1.length()); } catch (Exception e) { e.printStackTrace(); } return; } if (trim.contains(".")) { String[] split = trim.split("\\."); if (split.length > 1) { String s1 = split[1]; if (!TextUtils.isEmpty(s1)) { if (s1.length() >= MAX_PONIT_LENGTH + 1) { editText.setText(origin); try { String trim1 = editText.getText().toString().trim(); editText.setSelection(trim1.length()); } catch (Exception e) { e.printStackTrace(); } return; } } } if (split.length > 0) { String s1 = split[0]; if (s1.length() > MAX_LENGTH) { editText.setText(origin); try { String trim1 = editText.getText().toString().trim(); editText.setSelection(trim1.length()); } catch (Exception e) { e.printStackTrace(); } return; } } } else { if (trim.length() > MAX_LENGTH) { editText.setText(origin); try { String trim1 = editText.getText().toString().trim(); editText.setSelection(trim1.length()); } catch (Exception e) { e.printStackTrace(); } return; } } } } @Override public void afterTextChanged(Editable s) { } }
添加完工具类,下面来看看使用
edittext.addTextChangedListener(new InputNumWatcher(
edittext, 3, 2));
上面这行代码表示对edittext限制长度为3位(即最大值999),最多2位小数,当然你可以任意配置长度及小数位数。
一行代码就完了是不是很简单,喜欢的朋友就点个赞吧,谢谢!