android EditText alphabet-only validation

2019-08-31 06:19发布

问题:

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.

回答1:

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?



回答2:

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

How to create EditText accepts Alphabets only in android?



回答3:

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