美文网首页
Edittext的粘贴菜单(粘贴的数据带样式)

Edittext的粘贴菜单(粘贴的数据带样式)

作者: Mr低丶调 | 来源:发表于2019-11-18 19:41 被阅读0次

需求:粘贴只有纯文本不需要样式

方案:自定义Edittext重写菜单方法

public class MyEditText extends AppCompatEditText {
    static final int ID_SELECT_ALL = android.R.id.selectAll;
    static final int ID_UNDO = android.R.id.undo;
    static final int ID_REDO = android.R.id.redo;
    static final int ID_CUT = android.R.id.cut;
    static final int ID_COPY = android.R.id.copy;
    static final int ID_PASTE = android.R.id.paste;
    static final int ID_SHARE = android.R.id.shareText;
    static final int ID_PASTE_AS_PLAIN_TEXT = android.R.id.pasteAsPlainText;
    static final int ID_REPLACE = android.R.id.replaceText;
    static final int ID_ASSIST = android.R.id.textAssist;
    static final int ID_AUTOFILL = android.R.id.autofill;

    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        switch (id) {
            case android.R.id.paste:
                //调用剪贴板
                ClipboardManager clip = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                //改变剪贴板中Content
                if (clip != null) {
                    ClipData primaryClip = clip.getPrimaryClip();
                    if (primaryClip.getItemCount() > 0) {
                        setText(primaryClip.getItemAt(0).getText());
                    }
                }
                break;
            case ID_SELECT_ALL:
                return super.onTextContextMenuItem(id);
            case ID_UNDO:
                return super.onTextContextMenuItem(id);
            case ID_REDO:
                return super.onTextContextMenuItem(id);

            case ID_PASTE_AS_PLAIN_TEXT:
                return super.onTextContextMenuItem(id);

            case ID_CUT:
                return super.onTextContextMenuItem(id);

            case ID_COPY:
                return super.onTextContextMenuItem(id);

            case ID_REPLACE:
                return super.onTextContextMenuItem(id);
            case ID_SHARE:
                return super.onTextContextMenuItem(id);
            case ID_AUTOFILL:
                return super.onTextContextMenuItem(id);
        }
        return true;
    }
}

除了复写粘贴其余保持默认即可

相关文章

网友评论

      本文标题:Edittext的粘贴菜单(粘贴的数据带样式)

      本文链接:https://www.haomeiwen.com/subject/qbobictx.html