Go Android EditText 5 ways to restrict input characters

Source: Internet
Author: User

Recent projects require restricting the type of characters entered by the password, such as the inability to enter Chinese. Now summarize the various implementations of EditText to compare the pros and cons of various methods.


The first way: Set the InputType property of the EditText, which can be set through XML or Java files. If I want to set the form to show the password, I can set it as follows:

In XML, android:inputtype= "Textpassword"

In Java files, you can use Ev.setinputtype (Inputtype.type_text_variation_password);

InputType parameters such as phone, textpasswrod and so on, if you are interested, you can test it.



The second is to set the Android:digits property of the EditText, which can indicate which characters to support. For example, to limit the number and letters to be entered, you can:

Android:digits= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ". PS: Spit Groove, Write good tired, do not support interval operator ~ or-


The third type: use Textwather to monitor edittext character changes, and delete unwanted characters when content changes. In other words, users can casually press the keyboard, in the code immediately delete illegal characters. PS: The Common search function input box is to use Textwatcher to monitor the change of keyword, then check the data and show it. Example code: You can only enter letters or numbers, and if you want to support other characters, you may modify the Regex regular expression.

Evpwd =(EditText) Findviewbyid (R.id.ev_password); Evpwd.addtextchangedlistener (NewTextwatcher () {@Override Public voidBeforetextchanged (Charsequence charsequence,intIintI1,intI2) {} @Override Public voidOnTextChanged (Charsequence charsequence,intIintI1,intI2) {String editable=Evpwd.gettext (). toString (); String regEx= "[^a-za-z0-9]";//only letters or numbers can be enteredPattern p =Pattern.compile (regEx); Matcher m=P.matcher (editable); String Str= M.replaceall (""). Trim ();//remove characters that are not letters or numbers        if(!editable.equals (str))  {evpwd.settext (str); //set the character of the EditTextEvpwd.setselection (Str.length ());//to override the setting of the new cursor location because the character was deleted        }    }


The fourth kind: through Inputfilter to achieve. 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 position
spanned dest,//content currently displayed
int DStart,//current start position
int DEnd//current End position
);
Note: Intentfilter is a number of groups, which means you can write multiple filters!
The following implementation makes EditText only receive characters (numbers, letters), Character.isletterordigit will be Chinese also as letter, so write a regular judgment whether Chinese.

Evpwd.setfilters (Newinputfilter[]{NewInputfilter () {@Override PublicCharsequence Filter (Charsequence charsequence,intIintI1, spanned spanned,intI2,inti3) {String regex= "^[\u4e00-\u9fa5]+$"; BooleanIschinese =pattern.matches (Regex, charsequence.tostring ()); if(! Character.isletterordigit (Charsequence.charat (i)) | |Ischinese) {                return""; }            return NULL; }    }});



Fifth: Use EditText's Inputconnection property to restrict input characters. The new class inherits from EditText and overwrites the Oncreateinputconnection function, replacing edittext with Limittext in XML.

 Public classLimitedittextextendsEditText { PublicLimitedittext (Context context) {Super(context); }     PublicLimitedittext (Context context, AttributeSet attrs) {Super(context, attrs); }     PublicLimitedittext (context context, AttributeSet attrs,intdefstyleattr) {        Super(context, attrs, defstyleattr); }    /*** Input Method *@paramOutattrs *@return     */@Override Publicinputconnection oncreateinputconnection (editorinfo outattrs) {return NewInnerinputconnecttion (Super. Oncreateinputconnection (outattrs),false); }    classInnerinputconnecttionextendsInputconnectionwrapperImplementsinputconnection { PublicMinputconnecttion (inputconnection Target,Booleanmutable) {            Super(target, mutable); }        /*** Interception of input content * *@paramtext *@paramnewcursorposition *@return         */@Override Public BooleanCommittext (charsequence text,intnewcursorposition) {            //You can only enter letters or numbers            if(! Character.isletterordigit (Charsequence.charat (i)) | |Ischinese) {                return false; }            return Super. Committext (text, newcursorposition); } @Override Public Booleansendkeyevent (KeyEvent event) {return Super. Sendkeyevent (event); } @Override Public BooleanSetSelection (intStartintend) {            return Super. SetSelection (start, end); }    }}


These are all methods of edittext input restrictions, such as missing welcome supplement ~ ~ ~

Go Android EditText 5 ways to restrict input characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.