android EditText alphabet-only validation

2019-08-31 06:24发布

i wanted to validate a EditText and see if all of the letters are alphabet. it should be able to handle multiple EditText. i need a way to prevent user from entering anything other then alphabet.

        userTextInput=(EditText)findViewById(R.id.textInput);
    userTextInput.addTextChangedListener(this);

    public void afterTextChanged(Editable edit) {
    String textFromEditView = edit.toString();
            //first method
    ArrayList[] ArrayList;
    //ArrayList [] = new ArrayList;
    for(int i=0; i<=textFromEditView.length(); i++)
    {
        if(textFromEditView[i].isLetter() == false)
        {
            edit.replace(0, edit.length(), "only alphabets");
        }
    }
            //second method
    try
    {
        boolean isOnlyAlphabet = textFromEditView.matches("/^[a-z]+$/i");
        if(isOnlyAlphabet == false)
        {
            edit.replace(0, edit.length(), "only alphabets");
        }
    }
    catch(NumberFormatException e){}


}

for my second method the moment i enter anything, number or alphabet, my app crash. i have test my first method because it has the error textFromEditView must be an array type bue is resolved as string. can you help me to improve my code.

3条回答
Viruses.
2楼-- · 2019-08-31 06:43
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

How to create EditText accepts Alphabets only in android?

查看更多
Melony?
3楼-- · 2019-08-31 06:49

I think you'd do better using InputFilter:

InputFilter filter = new InputFilter() { 
        public CharSequence filter(CharSequence src, int start, int end,
                                                   Spanned d, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 
                        if (!Character.isLetter(src.charAt(i))) { 
                                return src.subSequence(start, i-1); 
                        } 
                } 
                return null; 
        } 
}; 

edit.setFilters(new InputFilter[]{filter});

Code modified from: How do I use InputFilter to limit characters in an EditText in Android?

查看更多
太酷不给撩
4楼-- · 2019-08-31 06:51

You can set the inputType of the EditText. More Information here and here.

查看更多
登录 后发表回答