特定字符数作为字母,后续字符作为数字

时间:2018-04-04 11:31:24

标签: android

我希望用户只输入前5个字符中的字母,下一个字符只能是数字。

我已阅读此链接的答案:Validation allow only number and characters in edit text in android

然而,当我尝试做我想做的事情时,我收到错误说:

  

java.lang.StringIndexOutOfBoundsException:length = 1;索引= 1                                                                                       在java.lang.String.charAt(本机方法)

我试图做我想要的代码。

InputFilter filter = new InputFilter() {
                public CharSequence filter(CharSequence source, int start,
                                           int end, Spanned dest, int dstart, int dend) {

                    for (int i = start;i < etLettersAndNumbers.getText().length();i++) {

                        if (etLettersAndNumbers.getText().length() < 4) {
                            if (!Character.isLetter(source.charAt(i))) {
                                return "";
                            }
                        }

                        if (etLettersAndNumbers.getText().length() >= 4) {
                            if (!Character.isDigit(source.charAt(i))) {
                                return "";
                            }
                        }
                    }

                    return null;
                }
            };
            etLettersAndNumbers.setFilters(new InputFilter[] {filter});

我正在使用动态EditText。

1 个答案:

答案 0 :(得分:2)

试试这个:

 public void set(final EditText etLettersAndNumbers) {
    etLettersAndNumbers.addTextChangedListener(new TextWatcher() {
        int len = 0;

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {


        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str = etLettersAndNumbers.getText().toString();
            char[] st = str.toCharArray();
            try {
                if (Character.isLetter(st[st.length - 1]) && st.length - 1 < 5) {
                    System.out.print("Nothing");
                } else if (!Character.isLetter(st[st.length - 1]) && st.length - 1 < 5) {
                    if(count>0)
                    etLettersAndNumbers.setText("");
                } else if (Character.isLetter(st[st.length - 1]) && st.length - 1 >= 5) {
                    if(count>0)
                    etLettersAndNumbers.setText("");
                }
            } catch (Exception e) {
                e.getMessage();
            }

        }


    });
}