Making an EditText field accept only letters and white spaces in Android

For some reason the inclusion of "\n" can not occur at the end of the string, I searched the Google documentation, most found nothing. the only way to achieve spaces and line break is including in the middle of the string. See the example I used in one of my apps.

android:digits="aãâáàbcçdeéfghiíjklmnoõôóòpqrstuvwxyzAÃÂÁÀBCÇDEÉFGHIÍJKLMNOÕÔÓÒPQRSTUVWXYZ1234567890@-_'+=(){}[]*%$#!?,.;\n: /?\\"

Below change worked for me:-

android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Put space in between your strings. If you put space at the end of a string it will get trimmed off automatically.

I have used space after ending of small letters and starting with capital letters.


Try this:

EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
    new InputFilter() {
        @Override
        public CharSequence filter(CharSequence cs, int start,
                    int end, Spanned spanned, int dStart, int dEnd) {
            // TODO Auto-generated method stub
            if(cs.equals("")){ // for backspace
                 return cs;
            }
            if(cs.toString().matches("[a-zA-Z ]+")){
                 return cs;
            }
            return "";
        }
    }
});

Tags:

Java

Android