EditView 可以监听到,文字改变的事件,可是粘贴和复制,如何监听呢, 看SDK 貌似没有类似的监听 其实这个问题也比较好处理, 首先我们来看一下在我们长按编辑框的时候, 会出现一个上下文的菜单,这个菜单中就有复制和粘贴,所以从这个角度出发,开始寻找TextView 中 弹出上下文的方法, 由于EditText 是从这里继承的,终于被我找到了
/** Called when a context menu option for the text view is selected. Currently
* this will be one of: {@link android.R.id#selectAll},
* {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText},
* {@link android.R.id#cut}, {@link android.R.id#copy},
* {@link android.R.id#paste}, {@link android.R.id#copyUrl},
* or {@link android.R.id#switchInputMethod}.
*/
public boolean onTextContextMenuItem(int id) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
if (!isFocused()) {
selStart = 0;
selEnd = mText.length();
}
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
if (min < 0) { min = 0;}
if (max < 0) {max = 0; }
ClipboardManager clip = (ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
switch (id) {
case ID_SELECT_ALL:
Selection.setSelection((Spannable) mText, 0,
mText.length());
return true;
case ID_START_SELECTING_TEXT:
MetaKeyKeyListener.startSelecting(this, (Spannable) mText);
return true;
case ID_STOP_SELECTING_TEXT:
MetaKeyKeyListener.stopSelecting(this, (Spannable) mText);
Selection.setSelection((Spannable) mText, getSelectionEnd());
return true;
case ID_CUT:
MetaKeyKeyListener.stopSelecting(this, (Spannable) mText);
if (min == max) {
min = 0;
max = mText.length();
}
clip.setText(mTransformed.subSequence(min, max));
((Editable) mText).delete(min, max);
return true;
case ID_COPY:
MetaKeyKeyListener.stopSelecting(this, (Spannable) mText);
if (min == max) {
min = 0;
max = mText.length();
}
clip.setText(mTransformed.subSequence(min, max));
return true;
case ID_PASTE:
MetaKeyKeyListener.stopSelecting(this, (Spannable) mText);
CharSequence paste = clip.getText();
if (paste != null) {
Selection.setSelection((Spannable) mText, max);
((Editable) mText).replace(min, max, paste);
}
return true;
case ID_COPY_URL:
MetaKeyKeyListener.stopSelecting(this, (Spannable) mText);
URLSpan[] urls = ((Spanned) mText).getSpans(min, max,URLSpan.class);
if (urls.length == 1) {
clip.setText(urls[0].getURL());
}
return true;
case ID_SWITCH_INPUT_METHOD:
InputMethodManager imm = InputMethodManager.peekInstance();
if (imm != null) {
imm.showInputMethodPicker();
}
return true;
case ID_ADD_TO_DICTIONARY:
String word = getWordForDictionary();
if (word != null) {
Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT");
i.putExtra("word", word);
getContext().startActivity(i);
}
return true;
}
return false;
}
上面就是 API 源码中的 上下文菜单响应事件的处理,我们只需要继承 EditText 将这部分代码重写,就可以获取到粘贴复制了,那么在做EditText 支持表情的时候,粘贴复制后,表情依然可以正常显示了。