最近的项目使用了EditText编辑文本,但需要屏蔽Emoji表情,于是在EditText的addTextChangedListener做了以下操作
private String before = "";
int couIndex;
boolean isAutoSet;
mTxtReplay.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!isAutoSet) {//判断是手动编辑录入还是通过setText自动设置的 如果是setText设置,则start为0,不再改变光标位置
couIndex = start;//记录最后一次光标所在位置
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
before = s.toString();
}
@Override
public void afterTextChanged(Editable s) {
if (isEmoji(mTxtReplay.getText().toString()) || mTxtReplay.getText().toString().contains("☺")) {//判断Emoje表情
isAutoSet = true;
mTxtReplay.setText(before); //setText的时候会调用onTextChanged并重置start位置为0,所以需要
isAutoSet = false;
mTxtReplay.setSelection(couIndex);//将最后一次输入文本的开始位置再设置到光标位置
}
if (mTxtReplay.getText().toString().length() > 1000) {
mTxtReplay.setText(before);
ToastUtil.showToast(CarOwnerQuestionReplayActivity.this, "最多输入1000字");
}
}
});
/**
* 判断方便是否是Emoji表情
* @param string
* @return
*/
public boolean isEmoji(String string) {
Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(string);
return m.find();
}