在Android中,可以通過對EditText設置setFilters方法,用代碼控制EditText的輸入長度,或控制輸入小數的位數等。
1.設置EditText的輸入長度
inputEdit.setFilters(new InputFilter[] { new InputFilter.LengthFilter(length)});
2.控制輸入小數的位數
- // 設置小數位數控制
- InputFilter lengthfilter = new InputFilter() {
- public CharSequence filter(CharSequence source, int start, int end,
- Spanned dest, int dstart, int dend) {
- // 刪除等特殊字符,直接返回
- if ("".equals(source.toString())) {
- return null;
- }
- String dValue = dest.toString();
- String[] splitArray = dValue.split("\\.");
- if (splitArray.length > 1) {
- String dotValue = splitArray[1];
- int diff = dotValue.length() + 1 - digLength;
- if (diff > 0) {
- return source.subSequence(start, end - diff);
- }
- }
- return null;
- }
- };
- inputEdit.setFilters(new InputFilter[] { lengthfilter });