Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict Edittext to some particular characters in android?

Tags:

android

searchEdit.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 &"));

I used the above statement for restricting my edittext to some characters,it is working well in my Motorolo(Android 2.3),but it is showing numeric keyboard in Google nexus.

Please provide the solution.

like image 740
user2376732 Avatar asked Dec 07 '25 23:12

user2376732


2 Answers

First try with adding the android:digits="abcde.....012345789" attribute.Although the android:digits specify that it is a numeric field but it accept letters as well.

OR

try this code..

t1 = (EditText)findViewById(R.id.text);

    t1.setFilters(new InputFilter[] {
            new InputFilter() {
                public CharSequence filter(CharSequence src, int start,
                        int end, Spanned dst, int dstart, int dend) {

                    if(src.equals("")){ // for backspace
                        return src;
                    }
                    if(src.toString().matches("[a-zA-Z0-9 ]*")) //put your constraints here
                    {
                        return src;
                    }
                    return "";
                }
            }
        }); 

OR

see an useful example from This Link

like image 99
ridoy Avatar answered Dec 10 '25 11:12

ridoy


Try to change the filter method of you Listener:

InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter(){
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (end > start) {

            char[] acceptedChars = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 
                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&', ' '};

            for (int index = start; index < end; index++) {                                         
                if (!new String(acceptedChars).contains(String.valueOf(source.charAt(index)))) { 
                    return ""; 
                }               
            }
        }
        return null;
    }

};
searchEdit.setFilters(filters);
like image 41
JoaoBiriba Avatar answered Dec 10 '25 11:12

JoaoBiriba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!