Please don't hurry to mark this message as "duplicated". I can't find an appropriate example. Suppose I'd like to restrict the char "{" in editText.
Let's consider a few variants of my code. I tried them on emulator only.
editName.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String txt=s.toString();
int len=txt.length();
toastDebug("len="+myIntToStr(len));
if (len>0) {
try {
int pos=txt.indexOf("{");
if (pos>=0) s.replace(pos,pos+1,"");
}
catch(Exception e) {}
}
}
If I type "{" quiickly it leads to "stackOverFlow" crash. Suppose I type "abcd{{{{{{{" slowly. For the first view it looks okay, no "{" in editText. But if I type backspace, it does not remove "abcd", it removes those invisible "{{{{{"
I tried to change the editText inside of "afterTextChanged". The code below causes stackOverflowError again.
public void afterTextChanged(Editable s) {
String txt=s.toString();
int len=txt.length();
if (len>0) {
try {
editName.setText(txt)
or
s.clear
s.append(txt)
}
catch(Exception e) {}
}
}
Many examples with code like this clear my editText after I type "{".
Well, I modified this code as follows:
editName.setFilters(new InputFilter[] { filterName });
private InputFilter filterName = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source==null) return null;
return source.toString().replace("{","");
}
};
Now it works. But my android:maxLength="25" does not work. It is possible to type any numbers of characters.
So I am puzzled how can I restrict simple character in editText. Any ideas? Thanks!