安卓粘贴文本时从EditText删除HTML

时间:2018-07-05 05:43:06

标签: android

也许这是一个非常简单的问题,但是我绝对不知道该怎么做。 当我从网站复制文本并将其粘贴到EditText时,我在EditText中获得HTML格式,如何避免这种情况?

我的EditText

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

3 个答案:

答案 0 :(得分:2)

将TextChangeListener添加到您的编辑文本视图

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) {

            }
        });

希望这会有所帮助

答案 1 :(得分:0)

感谢@gianhtran提出这个想法。这不能解决我的问题,但是有助于找到解决方案。这个解决方案看起来很不礼貌。如果您提供更好的服务,我会很高兴。

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) {

    }
});

答案 2 :(得分:0)

您必须像这样从html设置文本:

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