Zeon
Zeon

Reputation: 563

Android. Remove HTML from EditText when paste text

Maybe this is a very simple question, but I absolutely do not understand what to do. When I copy text from a website and paste it into the EditText, I get the HTML formating in the EditText, how to avoid this?

My EditText

<EditText
            android:id="@+id/field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

Upvotes: 3

Views: 553

Answers (3)

dreinoso
dreinoso

Reputation: 1689

You have to set the text from html like this:

myEditText.setText(Html.fromHtml(myHtmlString));

Upvotes: 0

Zeon
Zeon

Reputation: 563

Thank @gianhtran for the idea. This does not solve my problem, but it helped to find a solution. This solution looks very rude. I will be happy if you offer better.

boolean ignoreNext;

yourEditTextView.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (!ignoreNext 
            && count - before > 1 
            && charSequence instanceof SpannableStringBuilder) {
            String text = charSequence.toString();
            SpannableStringBuilder s = (SpannableStringBuilder) charSequence;
            s.clear();
            ignoreNext = true;
            s.append(text);
            ignoreNext = false;
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

Upvotes: 0

GianhTran
GianhTran

Reputation: 3711

add TextChangeListener to your edit text view

yourEditTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                charSequence = charSequence.toString()
                        .replaceAll("<(.*?)\\>", " ");//Removes all items in brackets
                charSequence =
                        charSequence.toString().replaceAll("<(.*?)\\\n", " ");//Must be undeneath
                charSequence = charSequence.toString()
                        .replaceFirst("(.*?)\\>",
                                " ");//Removes any connected item to the last bracket
                charSequence = charSequence.toString().replaceAll("&nbsp;", " ");
                charSequence = charSequence.toString().replaceAll("&amp;", " ");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

hope this helps

Upvotes: 3

Related Questions