没法处理,要不就是改framework的menu_item布局文件,但是有点BT;所以只能对用户的输入做限制,但考虑到中文和英文的宽度不一致,所以做了特殊处理。mToat是全局的静态变量,避免一直重复的出现toast。
public static void lengthFilter(final Context context, final EditText editText,
final int max_length, final int 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 = getCharacterNum(dest.toString());
int sourceLen = getCharacterNum(source.toString());
if (destLen + sourceLen > max_length) {
showToast(context, err_msg, Toast.LENGTH_SHORT);
return "";
}
return source;
}
};
editText.setFilters(filters);
}
public static int getCharacterNum(final String content) {
if (null == content || "".equals(content)) {
return 0;
} else {
return (content.length() + getChineseNum(content));
}
}
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;
}
public static void showToast(Context context, int text, int duration) {
if (mToast == null) {
mToast = Toast.makeText(context, text, duration);
} else {
mToast.setText(text);
mToast.setDuration(duration);
}
mToast.show();
}