Paste without rich text formatting into EditText

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);
    }
}

Erik's answer above removes few formatting, but not all. Hence I used:

CharacterStyle[] toBeRemovedSpans = string.getSpans(0, string.length(), CharacterStyle.class);

to remove all formatting.


The problem with clearSpans() was that it removed too much and the editText behaves weird thereafter. By following the approach in this answer I only remove the MetricAffectingSpan and it works fine then.

For me the only problem was the size of the text. If you have other problems you'd have to adjust what you want to remove.

public void afterTextChanged(Editable string)
{
    CharacterStyle[] toBeRemovedSpans = string.getSpans(0, string.length(),
                                                MetricAffectingSpan.class);
    for (int index = 0; index < toBeRemovedSpans.length; index++)
        string.removeSpan(toBeRemovedSpans[index]);
    }
}