Android edittext input length limit and prompt

Source: Internet
Author: User

 

Public static void lengthFilter (final Context context, final EditText editText, final int max_length, final String err_msg ){

 

InputFilter [] filters = new InputFilter [1];

 

Filters [0] = new InputFilter. LengthFilter (max_length ){

@ Override

Public CharSequence filter (CharSequence source, int start, int end,

Spanned dest, int dstart, int dend ){

Int destLen = StringUtils. getCharacterNum (dest. toString (); // obtain the number of characters (a Chinese character is counted as 2 characters)

Int sourceLen = StringUtils. getCharacterNum (source. toString ());

If (destLen + sourceLen> max_length ){

Toast. makeText (context, err_msg, Toast. LENGTH_SHORT). show ();

Return "";

}

Return source;

}

};

EditText. setFilters (filters );

}

 

 

 

Additional methods:

 

 

/**

* @ Description gets the number of characters in a string (including Chinese and English characters. One Chinese character is counted as two characters)

* @ Param content

* @ Return

*/

Public static int getCharacterNum (final String content ){

If (null = content | "". equals (content )){

Return 0;

} Else {

Return (content. length () + getChineseNum (content ));

}

}

 

/**

* @ Description returns the number of characters in the string, including the number of characters or full-width characters.

* @ Param s

* @ Return

*/

Public static int getChineseNum (String s ){

 

Int num = 0;

Char [] myChar = s. toCharArray ();

For (int I = 0; I <myChar. length; I ++ ){

If (char) (byte) myChar [I]! = MyChar [I]) {

Num ++;

}

}

Return num;

}

 

From Qingfeng's blog

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.