Android EditText Text length restrictions have a very simple way of restricting: adding Android:maxlength= "N" to EditText in an XML layout file
But this simple way may sometimes not meet some of the more serious needs, this time need to use another way to limit the length.
This is achieved by Inputfilter:
Private classNamelengthfilterImplementsInputfilter {intmax_en; String regEx= "[\\u4e00-\\u9fa5]"; PublicNamelengthfilter (intmax_en) { Super(); Max_en=max_en; } @Override PublicCharsequence Filter (charsequence source,intStartintend, spanned dest,intDStart,intdend) { intDestcount =dest.tostring (). Length ()+Getchinesecount (dest.tostring ()); intSourcecount =source.tostring (). Length ()+Getchinesecount (source.tostring ()); if(Destcount + sourcecount >max_en) { intSurpluscount = max_en-Destcount; String result= ""; intindex = 0; while(Surpluscount > 0) { Charc =Source.charat (index); if(Ischinest (c + ""))) { if(Sourcecount >= 2) {result+=C; } Surpluscount= SurplusCount-2; } Else{result+=C; Surpluscount= SurplusCount-1; } Index++; } returnresult; } Else { returnsource; } } Private intGetchinesecount (String str) {intCount = 0; Pattern P=Pattern.compile (regEx); Matcher m=P.matcher (str); while(M.find ()) { for(inti = 0; I <= m.groupcount (); i++) {Count= Count + 1; } } returncount; } Private Booleanischinest (String source) {returnpattern.matches (regEx, source); } }
The above is a custom filter, to the required edittext setting is OK:
Ed_nane.setfilters (filters);
Some code may be relatively low, but can be used.
Android EditText Text length limit (based on a Chinese character that takes two lengths similar to bytes)