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;
}
This is because the
maxLength
property sets anInputFilter
on yourEditText
. By callingEditText.setFilters(new InputFilter[] {<YOUR_FILTER>})
you are overriding all existing InputFilters including the one used bymaxLength
.To fix this, copy the array returned by
EditText.getFilters()
and add your own to it: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});
Try this code. Based on @Jozua answer
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:
so, something like (Pseudo code liveCoding) :