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

左心房为你撑大大i 提交于 2019-12-17 18:19:49

问题


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.


回答1:


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});   



回答2:


To limit what the user can enter as they type use a TextWatcher, discussed in this question Android: How can I validate EditText input?.

Better yet: Allow only selected charcters based on regex in an EditText




回答3:


The solution is to modify the these fields: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputMethod

Set the InputMethod of the EditText so that you can properly get what you need.




回答4:


Here is the regular expression

Pattern mPattern = Pattern.compile("^([1-9][0-9]{0,2})?(\\.[0-9]?)?$");
Matcher matcher = mPattern.matcher(loginNameString.toString());               
if(!matcher.find())
{
    //TODO
}


来源:https://stackoverflow.com/questions/10344493/android-how-to-set-acceptable-numbers-and-characters-in-edittext

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