请不要急于将此消息标记为“重复”。我找不到合适的例子。假设我想在editText中限制字符“ {”。
让我们考虑一下我的代码的一些变体。我只在模拟器上尝试过它们。
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) {}
}
}
如果我快速键入“ {”,将导致“ stackOverFlow”崩溃。假设我缓慢输入“ abcd {{{{{{{}”。对于第一个视图,看起来不错,editText中没有“ {”。但是,如果我键入退格键,则不会删除“ abcd”,而是会删除那些不可见的“ {{{{{””
我试图在“ afterTextChanged”内部更改editText。下面的代码再次导致stackOverflowError。
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) {}
}
}
当我键入“ {”后,许多带有此类代码的示例都会清除我的editText。
好吧,我将这段代码修改如下:
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("{","");
}
};
现在可以了。但是我的android:maxLength =“ 25”无法正常工作。可以键入任意数量的字符。
所以我很困惑如何限制editText中的简单字符。有任何想法吗?谢谢!
您可以EditText
通过TextWatcher
在小部件上设置a并在下面插入逻辑来限制用户可以输入的字符:
// we are interested in this callback
@Override
public void afterTextChanged(Editable s) {
String result = s.toString().replaceAll("\\{", "");
if (!s.toString().equals(result)) {
edit.setText(result); // "edit" being the EditText on which the TextWatcher was set
edit.setSelection(result.length()); // to set the cursor at the end of the current text
}
}
的\\
需要(以及其他字符),因为该{
字符具有以图案的特殊含义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句