Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

android - Allow only selected charcters based on regex in an EditText

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...