Android之EditText设置长度限制提示和自动添加空格

EditText在输入过程中我们有时需要给客户长度限制并提示来提升用户的客户体验

这个在上一篇关于EditText的使用中基本介绍了。


今天我们介绍下如何让我们的EditText在输入过程中 【147 6323 1344】带有空格输入的模式

首先我们在上篇介绍过 TextWatcher 的使用 http://blog.csdn.net/qq_35352552/article/details/56479983


这里的 自动添加空格 主要就是用的它来实现的

private final TextWatcher textWatcher = new TextWatcher() {
        int beforeTextLength = 0;
        int onTextLength = 0;
        boolean isChanged = false;

        int location = 0;   // 记录光标的位置
        private char[] tempChar;
        private StringBuffer buffer = new StringBuffer();
        int spacingNumberB = 0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            beforeTextLength = s.length();
            if (buffer.length() > 0) {
                buffer.delete(0, buffer.length());
            }
            spacingNumberB = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    spacingNumberB++;
                }
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onTextLength = s.length();
            buffer.append(s.toString());
            if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                isChanged = false;
                return;
            }
            isChanged = true;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (isChanged) {
                location = PowerfulEditText.this.getSelectionEnd();
                int index = 0;
                while (index < buffer.length()) {
                    if (buffer.charAt(index) == ' ') {
                        buffer.deleteCharAt(index);
                    } else {
                        index++;
                    }
                }

                index = 0;
                int spacingNumberC = 0;
                while (index < buffer.length()) {
                    if (mIndexList.contains(index)) { // 包含插入空格
                        buffer.insert(index, ' ');
                        spacingNumberC++;
                    }
                    index++;
                }

                if (spacingNumberC > spacingNumberB) {
                    location += (spacingNumberC - spacingNumberB);
                }

                tempChar = new char[buffer.length()];
                buffer.getChars(0, buffer.length(), tempChar, 0);
                String str = buffer.toString();
                if (location > str.length()) {
                    location = str.length();
                } else if (location < 0) {
                    location = 0;
                }

                PowerfulEditText.this.setText(str);
                Editable table = PowerfulEditText.this.getText();
                Selection.setSelection(table, location);
                isChanged = false;
            }
        }
    };

然后就是监听长度限制

 class MaxTextLengthFilter implements InputFilter {

        private Toast mToast = null;
        private int iBlankCount = 0;
        private int iMax;
        private int iKeep;

        public MaxTextLengthFilter(int max) {
            iMax = max;
            mToast = ToastUtil.showSingleTxtHint(String.format("长度不能超过%d位", iMax), Toast.LENGTH_SHORT);
        }

        public MaxTextLengthFilter(int max, int blankCount) {
            iMax = max;
            iBlankCount = blankCount;
            mToast = ToastUtil.showSingleTxtHint(String.format("长度不能超过%d位", iMax), Toast.LENGTH_SHORT);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int d_start, int d_end) {
            if (iBlankCount != 0) {
                iKeep = (iMax + iBlankCount) - (dest.length() - (d_end - d_start));
            } else {
                iKeep = iMax - (dest.length() - (d_end - d_start));
            }

            if (iKeep < (end - start)) {
                mToast.show();
            }
            if (iKeep <= 0) {
                return "";
            } else if (iKeep >= end - start) {
                return null;
            } else {
                return source.subSequence(start, start + iKeep);
            }
        }
    }

这里 Toast 是我自定义的自己动手改一下就好了,还有就是我用了两个不同参数的监听 其作用就是在想要输入有空格样式加设空格的长度


接下来我们就自定义一下自己的EditText 吧! 直接复制黏贴就好啦

/**
 * 作者:CoolTone
 * 描述:强大功能的EditText
 */
public class PowerfulEditText extends EditText {

    private List mIndexList;

    public PowerfulEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PowerfulEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    // 设置最大长度
    public void setMaxLength(int length) {
        if (length > 0) {
            this.setFilters(new InputFilter[]{new MaxTextLengthFilter(length)});
        }
    }

    // 设置最大长度和空格
    public void setMaxLengthAndSpacing(int length, List indexList) {
        mIndexList = indexList;
        this.addTextChangedListener(textWatcher);
        if (length > 0) {
            this.setFilters(new InputFilter[]{new MaxTextLengthFilter(length, indexList.size())});
        }
    }

    class MaxTextLengthFilter implements InputFilter {

        private Toast mToast = null;
        private int iBlankCount = 0;
        private int iMax;
        private int iKeep;

        public MaxTextLengthFilter(int max) {
            iMax = max;
            mToast = ToastUtil.showSingleTxtHint(String.format("长度不能超过%d位", iMax), Toast.LENGTH_SHORT);
        }

        public MaxTextLengthFilter(int max, int blankCount) {
            iMax = max;
            iBlankCount = blankCount;
            mToast = ToastUtil.showSingleTxtHint(String.format("长度不能超过%d位", iMax), Toast.LENGTH_SHORT);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int d_start, int d_end) {
            if (iBlankCount != 0) {
                iKeep = (iMax + iBlankCount) - (dest.length() - (d_end - d_start));
            } else {
                iKeep = iMax - (dest.length() - (d_end - d_start));
            }

            if (iKeep < (end - start)) {
                mToast.show();
            }
            if (iKeep <= 0) {
                return "";
            } else if (iKeep >= end - start) {
                return null;
            } else {
                return source.subSequence(start, start + iKeep);
            }
        }
    }

    private final TextWatcher textWatcher = new TextWatcher() {
        int beforeTextLength = 0;
        int onTextLength = 0;
        boolean isChanged = false;

        int location = 0;   // 记录光标的位置
        private char[] tempChar;
        private StringBuffer buffer = new StringBuffer();
        int spacingNumberB = 0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            beforeTextLength = s.length();
            if (buffer.length() > 0) {
                buffer.delete(0, buffer.length());
            }
            spacingNumberB = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    spacingNumberB++;
                }
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onTextLength = s.length();
            buffer.append(s.toString());
            if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                isChanged = false;
                return;
            }
            isChanged = true;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (isChanged) {
                location = PowerfulEditText.this.getSelectionEnd();
                int index = 0;
                while (index < buffer.length()) {
                    if (buffer.charAt(index) == ' ') {
                        buffer.deleteCharAt(index);
                    } else {
                        index++;
                    }
                }

                index = 0;
                int spacingNumberC = 0;
                while (index < buffer.length()) {
                    if (mIndexList.contains(index)) {
                        buffer.insert(index, ' ');
                        spacingNumberC++;
                    }
                    index++;
                }

                if (spacingNumberC > spacingNumberB) {
                    location += (spacingNumberC - spacingNumberB);
                }

                tempChar = new char[buffer.length()];
                buffer.getChars(0, buffer.length(), tempChar, 0);
                String str = buffer.toString();
                if (location > str.length()) {
                    location = str.length();
                } else if (location < 0) {
                    location = 0;
                }

                PowerfulEditText.this.setText(str);
                Editable table = PowerfulEditText.this.getText();
                Selection.setSelection(table, location);
                isChanged = false;
            }
        }
    };
}

这里如果报红的话应该是我自己定义的其他东西,改成系统的就好了!

这里监听有两种

setMaxLength(int length)    直接设置长度限制
setMaxLengthAndSpacing(int length, List indexList)   设置长度限制并且添加空格

* 这里的空格设置 是以 list 添加进去的比如手机的

 List mListPhone = new ArrayList();
 mListPhone.add(3);
 mListPhone.add(8);

一定要算好下标

这样就Ok了




你可能感兴趣的:(Android自定控件)