android edittext 輸入長度限制並提示 – Android移動開發技術文章_手機開發 Android移動開發教學課程

 

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()); //獲取字符個數(一個中文算2個字符)

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);

}

 

 

 

附加方法:

 

 

/**

 * @description 獲取一段字符串的字符個數(包含中英文,一個中文算2個字符)

 * @param content

 * @return

 */

public static int getCharacterNum(final String content) {

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

return 0;

}else {

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

}

}

 

/**

* @description 返回字符串裡中文字或者全角字符的個數

* @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;

}

 

摘自 青峰的博客

發佈留言