Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

I have an EditText field in my project which stands for the full name of the person.So I want only letters and spaces to be allowed in it.So I tried the following in the XML file

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "

But it didn't work.Can anyone tell me how to do it?

like image 392
Achuthan M Avatar asked Sep 26 '14 10:09

Achuthan M


2 Answers

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 "";
        }
    }
});
like image 87
Batuhan Coşkun Avatar answered Oct 01 '22 13:10

Batuhan Coşkun


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.

like image 42
Tanu Avatar answered Oct 01 '22 14:10

Tanu