过滤 Edittext 以接受不以 0 开头的单词或数字

Filter Edittext to accept word or number that doesn't start with 0

我想做的是使 Editext 只包含不以零开头的单词或数字,所以我这样做了

mPatentNameET.setFilters(new InputFilter[] {
                new InputFilter() {
                    public CharSequence filter(CharSequence src, int start,
                                               int end, Spanned dst, int dstart, int dend) {
                        if(src.equals("")){ // for backspace
                            return src;
                        }
                        if(src.toString().matches("[a-zA-Z ]+")  ||
                                src.toString().matches("^[123456789][0-9]$")){
                            return src;
                        }
                        return "";
                    }
                }
        });

但效果不佳,我想从 EditText 接受例如 "Test" 或 "546",抱歉我的英语不好

我是这样解决的:)

mPatentNameET.setFilters(new InputFilter[] {
                new InputFilter() {
                    public CharSequence filter(CharSequence src, int start,
                                               int end, Spanned dst, int dstart, int dend) {
                        if(src.equals("")){ // for backspace
                            return src;
                        }
                        if((mPatentNameET.getText().toString() + src).matches("[a-zA-Z ]+")  ||
                                (mPatentNameET.getText().toString() + src).matches("^[123456789][0-9]*$")){
                            return src;
                        }
                        return "";
                    }
                }
        });

您可以使用 TextWatcher。像这样:

    mPatentNameET.addTextChangedListener(new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            String EditTextString= tx.getText().toString();
            if(EditTextString.charAt(0).equals("0")){
                //TODO return when starting with 0
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }

    });