Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

android - Paste without rich text formatting into EditText

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...