使EditText字段仅接受Android中的字母和空格 [英] Making an EditText field accept only letters and white spaces in Android

查看:612
本文介绍了使EditText字段仅接受Android中的字母和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个EditText字段代表该人的全名。所以我只想在其中允许使用字母和空格。所以我在 XML中尝试了以下内容 file

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?

推荐答案

试试这个:

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

这篇关于使EditText字段仅接受Android中的字母和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆