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

时间:2015-02-20 20:17:08

标签: java android filter android-edittext

我要做的是制作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”,抱歉我的英文不好

2 个答案:

答案 0 :(得分:0)

我像这样解决它:)

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 "";
                    }
                }
        });

答案 1 :(得分:0)

你可以使用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

        }

    });