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 view to ignore rich text formatting? Or can I catch the paste event and remove it before it gets set? How would I do that?
UPDATE: So I realized that the editText.getText()
gives me a SpannableString
that contains some formatting. I can get rid of that by calling .clearSpans();
on it. BUT I cannot do anything like that in editText.addTextChangedListener(new TextWatcher() { … }
because it gets terribly slow and the UI only updates when I leave the editText view.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With