Summary of the method of restricting input character types in Android EditText
Preface:
Recently, I need to limit the type of EditText input characters, so I have sorted out the methods that can implement this function:
1. The first method is to implement it through EditText's inputType, which can be set through XML or Java files. If I want to set it to display the password, I can set it like this:
In xml
Android:inputType="textPassword"
In java files, you can use (InputType.TYPE_TEXT_VARIATION_PASSWORD);
Of course, there are more other properties for input settings.
2. The second type is set through the android:digits attribute. This way, you can point out the characters to be displayed. For example, I want to limit only the numbers to be displayed, so you can:
android:digits="0123456789"
If there is a lot of content to be displayed, it will be more troublesome, and write the content to be displayed in it in turn.
3. Judgment through regular expressions. The following examples allow only letters, numbers and Chinese characters to be displayed.
public static String stringFilter(String str)throws PatternSyntaxException{ // Only letters, numbers and Chinese characters are allowed String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]"; Pattern p = (regEx); Matcher m = (str); return ("").trim(); }
Then you need to call this function in the onTextChanged() of TextWatcher.
@Override public void onTextChanged(CharSequence ss, int start, int before, int count) { String editable = ().toString(); String str = stringFilter(()); if(!(str)){ (str); //Set the new cursor location (()); } }
4. Implementation through InputFilter.
To implement the InputFilter filter, you need to override a method called filter.
public abstract CharSequence filter ( CharSequence source, //Input text int start, //Start position int end, //End Location Spanned dest, //The current content displayed int dstart, //Current start position int dend //The current end position);
The following implementation makes EditText only receive characters (numbers, letters and Chinese characters) and "-" and "_", and will also regard Chinese as Letter.
(new InputFilter[] { new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if ( !((i)) && !((i)) .equals("_") && !((i)) .equals("-")) { return ""; } } return null; } });
In addition, using InputFilter can also limit the number of characters entered, such as
EditText tv =newEditText(this); int maxLength =10; InputFilter[] fArray =new InputFilter[1]; fArray[0]=new (maxLength); (fArray);
The above code can limit the maximum number of characters entered to 10.
Thank you for reading, I hope it can help you. Thank you for your support for this site!