使用setFilters时,无法正确应用EditText maxLength属性 [英] EditText maxLength property not applied properly when setFilters is used

查看:113
本文介绍了使用setFilters时,无法正确应用EditText maxLength属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在EditText上使用setFilter方法来处理特殊字符时,maxLength属性无法正常工作.我的代码在下面.

When I use setFilter method on an EditText to handle special characters, maxLength property is not working as expected. My code is below.

editName = (EditText)findViewById(R.id.rna_editTextName);
        editName.setFilters(new InputFilter[]{getFilteredChars()}); 


        //Below method returns filtered characters.
       public InputFilter getFilteredChars() 
       {
           InputFilter filter = 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', ' ' ,'.', '\''};

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

推荐答案

这是因为maxLength属性在EditText上设置了InputFilter.通过调用EditText.setFilters(new InputFilter[] {<YOUR_FILTER>}),您将覆盖所有现有的InputFilter,包括由maxLength使用的InputFilter.

This is because the maxLength property sets an InputFilter on your EditText. By calling EditText.setFilters(new InputFilter[] {<YOUR_FILTER>}) you are overriding all existing InputFilters including the one used by maxLength.

要解决此问题,请复制EditText.getFilters()返回的数组并将其添加到其中:

To fix this, copy the array returned by EditText.getFilters() and add your own to it:

InputFilter[] editFilters = edit.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = <YOUR_FILTER>;
edit.setFilters(newFilters);

这篇关于使用setFilters时,无法正确应用EditText maxLength属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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