EditText maxLength property not applied properly when setFilters is used

帅比萌擦擦* 提交于 2019-11-30 15:17:23

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.

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

Try this code. Based on @Jozua answer

    /**
 * Adds filter to EditText preserving other filters.
 * 
 * @param editText
 * @param filter
 */
public static void setFilter(EditText editText, InputFilter filter) {
InputFilter curFilters[] = editText.getFilters();

if (curFilters != null) {
    InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
    System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
    newFilters[curFilters.length] = filter;
    editText.setFilters(newFilters);
} else {
    editText.setFilters(new InputFilter[] { filter });
}
}

You may add multiple filter at array. Like maximum character limit and special character filter at your editText.

editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_CHARACTER_LIMIT),SpecialCharacterInputFilter});

while setting maxlenth property of edittext programatically

please show use the code.

Wild Guess: the problem may be that you set the maxLength in the layout. By calling setFilters() this behavior is replace by the one of your Filter.

Solution: use more that one filter or implement the maxLenght behavior in your getFilteredChars() filter.

EDIT: you may want to look at http://developer.android.com/reference/android/text/InputFilter.LengthFilter.html

and for you question in the comment, from the doc:

when the buffer is going to replace the range dstart … dend of dest with the new text from the range start … end of source

so, something like (Pseudo code liveCoding) :

dest.lenght - (dend-dstart) + (end-start)  = new legnth
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!