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
454 views
in Technique[技术] by (71.8m points)

validation - Android : How to set acceptable numbers and characters in EditText?

I have to set acceptable characters "0123456789" and "semicolon" in the EditText. Below is the code I'm using.

android:digits="0123456789;"
android:inputType="number|text

The problem with that implementation is in HTC phones, semicolon can't be entered but in Samsung and Sony Ericsson, semicolon can be entered. Another problem is when I entered semicolon in Samsung and Sony Ericsson, semicolon can't be deleted. Is there any missing property in the above code? Thanks in advance.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Android provides an easy way to edit text fields by modifying the layout xml and adding an android:inputType="text". This lets you easily create some basic validations like numbers, decimal, phone or emails. But there's no parameter for alphanumeric (i.e. no special characters). To do this, you need to use an input filter like below and set the fields you want to validate with that filter in code. This input filter

 InputFilter alphaNumericFilter = new InputFilter() {   
     @Override  
     public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5)  
     {  
         for (int k = arg1; k < arg2; k++) {   
             if (!Character.isLetterOrDigit(arg0.charAt(k))) {   
             return ""; 
             }   //the first editor deleted this bracket when it is definitely necessary...
         }
         return null;
     }  
 };   
 mFirstName.setFilters(new InputFilter[]{ alphaNumericFilter});   

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

...