package com.syswin.toon.view; import android.content.ClipboardManager; import android.content.Context; import android.text.Editable; import android.text.SpannableString; import android.util.AttributeSet; import android.widget.EditText; import com.syswin.toon.view.emoji.EmojiUtils; /** * 聊天自定义EditText * Created by Administrator on 2015/1/21. */ public class ChatEditText extends EditText{ public ChatEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ChatEditText(Context context, AttributeSet attrs) { super(context, attrs); } public ChatEditText(Context context) { super(context); } @Override public boolean onTextContextMenuItem(int id) { switch (id) { case android.R.id.paste: ClipboardManager clip = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); int index = getSelectionStart();// 光标所在位置 String value = clip.getText().toString(); clip.setText(""); Editable edit = getEditableText();// 获取EditableText SpannableString spannableString = null; String zhengze = "\\[[^\\[\\]]{1,3}\\]"; // 正则表达式,用来判断消息内是否有表情 try { spannableString = EmojiUtils.getExpressionString(getContext(), value, zhengze, 0.7f, false); } catch (Exception e) { e.printStackTrace(); } if(spannableString == null){ edit.insert(index, "表情匹配错误");//把转换后的CharSequence插入到光标所在位置 }else{ edit.insert(index, spannableString);//把转换后的CharSequence插入到光标所在位置 } //do something break; default: break; } return super.onTextContextMenuItem(id); } }
复写EditText 从而实现EditText中粘贴事件处理,从而将匹配符替换为表情
时间: 2024-11-10 04:51:06