Edittext不允許輸入Emoji表情—解決了谷歌拼音輸入法會奔潰的bug


項目中不允許輸入Emoji表情,從網上找來例子,復制、粘貼到項目中,以為妥妥的交工,但是無意中用了帶有谷歌拼音輸入法的手機跑了項目,發現確是奔潰,於是找解決方案,其實很簡單,請看以下代碼:

標注的紅色部分為關鍵。(額,不太回調代碼格式,代碼格式不太協調,委屈看官了。。)

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.Toast;

public class ContainsEmojiEditText extends EditText {
//輸入表情前的光標位置
private int cursorPos;
//輸入表情前EditText中的文本
private String inputAfterText;
//是否重置了EditText的內容
private boolean resetText;

private Context mContext;

public ContainsEmojiEditText(Context context) {
super(context);
this.mContext = context;
initEditText();
}

public ContainsEmojiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
initEditText();
}

public ContainsEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
initEditText();
}

// 初始化edittext 控件
private void initEditText() {
cursorPos = getSelectionEnd();
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int before, int count) {
if (!resetText) {
cursorPos = getSelectionEnd();
//這里用s.toString()而不直接用s是因為如果用s,
// 那么,inputAfterText和s在內存中指向的是同一個地址,s改變了,
// inputAfterText也就改變了,那么表情過濾就失敗了
inputAfterText = s.toString();

}

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!resetText) {

if(before != 0){

return;

}
if (count >= 2) {//表情符號的字符長度最小為2
CharSequence input = s.subSequence(cursorPos, cursorPos + count );
if (containsEmoji(input.toString())) {
resetText = true;
Toast.makeText(mContext, "不支持輸入Emoji表情符號", Toast.LENGTH_SHORT).show();
//是表情符號就將文本還原為輸入表情符號之前的內容
setText(inputAfterText);
CharSequence text = getText();
if (text instanceof Spannable) {
Spannable spanText = (Spannable) text;
Selection.setSelection(spanText, text.length());
}
}
}
} else {
resetText = false;
}
// cursorPos = getSelectionEnd();
}

@Override
public void afterTextChanged(Editable s) {

}
});
}


/**
* 檢測是否有emoji表情
*
* @param source
* @return
*/
public static boolean containsEmoji(String source) {
int len = source.length();
for (int i = 0; i < len; i++) {
char codePoint = source.charAt(i);
if (!isEmojiCharacter(codePoint)) { //如果不能匹配,則該字符是Emoji表情
return true;
}
}
return false;
}

/**
* 判斷是否是Emoji
*
* @param codePoint 比較的單個字符
* @return
*/
private static boolean isEmojiCharacter(char codePoint) {
return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
(codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
&& (codePoint <= 0x10FFFF));
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM