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

前端 未结 10 717
别跟我提以往
别跟我提以往 2020-12-18 21:09

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

10条回答
  •  一向
    一向 (楼主)
    2020-12-18 21:30

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

提交回复
热议问题