Allow only selected charcters based on regex in an EditText

萝らか妹 提交于 2019-12-17 19:02:09

问题


I want to allow users only to type certain characters based on the a regex in my android applications. How do I achieve it?


回答1:


Used a TextWatcher as @Matt Ball suggested.

@Override
public void afterTextChanged(Editable s) {
      String text = s.toString();
      int length = text.length();

      if(length > 0 && !Pattern.matches(PATTERN, text)) {
           s.delete(length - 1, length);
      }
}

Edit Although the TextWatcher works, it would be cleaner to use an InputFilter. Check this example.




回答2:


Try this: If the character to type matches /[a-zA-Z0-9{insert valid characters here}]/ then allow it, otherwise don't.



来源:https://stackoverflow.com/questions/4180770/allow-only-selected-charcters-based-on-regex-in-an-edittext

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