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