EditText限制输入emoji表情总结

来源:互联网 发布:2016年大数据产业规模 编辑:程序博客网 时间:2024/05/16 17:30
 

实际的项目开发中很多时候要求密码输入时不能输入emoji表情,看了很多大神的博客,决定总结一下,以备以后使用。(注意:有一个单字符的表情是可以输入的···)

// 输入表情前的光标位置private int cursorPos;// 输入表情前EditText中的文本private String inputAfterText;// 是否重置了EditText的内容private boolean resetText;// edittext监听private TextWatcher TextWatcher = new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int before,int count) {try {if (!resetText) {cursorPos = userpwd.getSelectionEnd();// 这里用s.toString()而不直接用s是因为如果用s,// 那么,inputAfterText和s在内存中指向的是同一个地址,s改变了,// inputAfterText也就改变了,那么表情过滤就失败了inputAfterText = s.toString();}} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {try {if (!resetText) {if (count >= 2) {// 表情符号的字符长度最小为2CharSequence input = s.subSequence(cursorPos, cursorPos+ count);if (CommonUtils.containsEmoji(input.toString())) {resetText = true;showMessage("不允许输入表情");// 是表情符号就将文本还原为输入表情符号之前的内容userpwd.setText(inputAfterText);CharSequence text = userpwd.getText();if (text instanceof Spannable) {Spannable spanText = (Spannable) text;Selection.setSelection(spanText, text.length());}}}} else {resetText = false;}} catch (Exception e) {e.printStackTrace();}}@Overridepublic void afterTextChanged(Editable editable) {try {Editable e = userpwd.getText();int position = e.length();Selection.setSelection(e, position);} catch (Exception e) {e.printStackTrace();}}};/** * 检测是否有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 */public 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));}

其中,userpwd为需要限制的EditText,然后在初始化组件的时候调用addTextChangedListener(),比如:userpwd.addTextChangedListener(TextWatcher) 即可。

1 0
原创粉丝点击