EditText智能限制小数点前后分别保留几位
需求
- 可以分别限制小数点前面几位,和小数点后几位
- 首位输入0时,第二位只能输入小数点
- 首位输入小数点,默认显示0.
- 嘻嘻!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
public static void setEditTextLimit(final int frontPoint, final int behindPoint, final EditText... editTexts) { if (editTexts != null && editTexts.length > 0) { for (final EditText editText : editTexts) { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == frontPoint + 1 && !s.toString().contains(".")) { editText.setText(s.toString().substring(0, frontPoint)); editText.setSelection(frontPoint); } if (editText.getText().toString().indexOf(".") >= 0) { if (editText.getText().toString().indexOf(".", editText.getText().toString().indexOf(".") + 1) > 0) { editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length() - 1)); editText.setSelection(editText.getText().toString().length()); } } if (s.toString().contains(".")) { if (s.length() - 1 - s.toString().indexOf(".") > behindPoint) { s = s.toString().subSequence(0, s.toString().indexOf(".") + behindPoint+1); editText.setText(s); editText.setSelection(s.length()); } } if (s.toString().trim().substring(0).equals(".")) { s = "0" + s; editText.setText(s); editText.setSelection(2); } if (s.toString().startsWith("0") && s.toString().trim().length() > 1) { if (!s.toString().substring(1, 2).equals(".")) { editText.setText(s.subSequence(0, 1)); editText.setSelection(1); return; } } }
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override public void afterTextChanged(Editable s) { }
}); } } }
|
xml别忘了
1
| android:inputType="numberDecimal"
|