Android EditText Text length limit (based on a Chinese character that takes two lengths similar to bytes)

Source: Internet
Author: User

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)

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.