1.需要的工具类
public class StringUtil {
/**
* 获取字符串的长度,中文占一个字符,英文数字占半个字符
*
* @param value
* 指定的字符串
* @return 字符串的长度
*/
public static int length(String value) {
double valueLength = 0;
String chinese = "[\u4e00-\u9fa5]";
// 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
for (int i = 0; i < value.length(); i++) {
// 获取一个字符
String temp = value.substring(i, i + 1);
// 判断是否为中文字符
if (temp.matches(chinese)) {
// 中文字符长度为1
valueLength += 1;
} else {
// 其他字符长度为0.5
valueLength += 0.5;
}
}
// 进位取整
return (int) (Math.ceil(valueLength) * 2);
}
//输入框文字超长时间,转换字符内容
public static String get12Sub(String value) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
// 获取一个字符
String temp = value.substring(i, i + 1);
sb.append(temp);
Paint paint = new Paint();
Rect rect = new Rect();
paint.getTextBounds(sb.toString(), 0, sb.toString().length(), rect);
if (rect.width() >= 118) {
sb.append("…");
Log.i("aaa", sb.toString());
return sb.toString();
}
}
return value;
}
}
2.自定义EditText,实现addTextChangedListener 和 onFocusChange方法
public MyEditorText(Context context, AttributeSet attrs) {
super(context, attrs);
this.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (StringUtil.length(MyEditorText.this.getText().toString()) >= 24) {
int length = MyEditorText.this.getText().toString().length();
InputFilter[] filters = {new InputFilter.LengthFilter(length)};
MyEditorText.this.setFilters(filters);
} else {
InputFilter[] filters = {new InputFilter.LengthFilter(24)};
MyEditorText.this.setFilters(filters);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
this.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String value = MyNormalEditorText.this.getText().toString();
textValue = value;
String show = StringUtil.get12Sub(value);
Log.i("aaa", "show......" + show);
MyNormalEditorText.this.setText(show);
} else {
try {
MyNormalEditorText.this.setText(textValue);
MyNormalEditorText.this.setSelection(textValue.length());
} catch (Exception e) {
Log.i("aaa", "输入框光标有误 :" + e.toString());
}
}
}
});
}
}
欢迎转载,但请标注原创地址!