Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

java - Making an EditText field accept only letters and white spaces in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 "";
        }
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...