Paste without rich text formatting into EditText

后端 未结 4 619
一个人的身影
一个人的身影 2020-12-16 12:09

If I copy/paste text from Chrome for Android into my EditText view it gets messed up, apparently due to rich text formatting.

Is there a way to tell the EditText vie

4条回答
  •  伪装坚强ぢ
    2020-12-16 12:45

    A perfect and easy way: Override the EditText's onTextContextMenuItem and intercept the android.R.id.paste to be android.R.id.pasteAsPlainText

    @Override
    public boolean onTextContextMenuItem(int id) {
        if (id == android.R.id.paste) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                id = android.R.id.pasteAsPlainText;
            } else {
                onInterceptClipDataToPlainText();
            }
        }
        return super.onTextContextMenuItem(id);
    }
    
    
    private void onInterceptClipDataToPlainText() {
        ClipboardManager clipboard = (ClipboardManager) getContext()
            .getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = clipboard.getPrimaryClip();
        if (clip != null) {
            for (int i = 0; i < clip.getItemCount(); i++) {
                final CharSequence paste;
                // Get an item as text and remove all spans by toString().
                final CharSequence text = clip.getItemAt(i).coerceToText(getContext());
                paste = (text instanceof Spanned) ? text.toString() : text;
                if (paste != null) {
                    ClipBoards.copyToClipBoard(getContext(), paste);
                }
            }
        }
    }
    

    And the copyToClipBoard:

    public class ClipBoards {
    
        public static void copyToClipBoard(@NonNull Context context, @NonNull CharSequence text) {
            ClipData clipData = ClipData.newPlainText("rebase_copy", text);
            ClipboardManager manager = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
            manager.setPrimaryClip(clipData);
        }
    }
    

提交回复
热议问题