不带富文本格式的粘贴到 EditText

时间:2023-05-03
本文介绍了不带富文本格式的粘贴到 EditText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果我从 Chrome for Android 复制/粘贴文本到我的 EditText 视图中,它会变得一团糟,显然是由于富文本格式.

If I copy/paste text from Chrome for Android into my EditText view it gets messed up, apparently due to rich text formatting.

有没有办法告诉 Edi​​tText 视图忽略富文本格式?或者我可以在粘贴事件设置之前将其删除吗?我该怎么做?

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?

更新:所以我意识到 editText.getText() 给了我一个 SpannableString 包含一些格式.我可以通过调用 .clearSpans(); 来摆脱它.但是我不能在 editText.addTextChangedListener(new TextWatcher() { ... } 中做类似的事情,因为它变得非常慢,并且 UI 仅在我离开 editText 视图时更新.

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.

推荐答案

clearSpans() 的问题是它删除了太多,并且此后editText 的行为很奇怪.通过遵循 this answer 中的方法,我只删除了 MetricAffectingSpan 和那么它工作正常.

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

这篇关于不带富文本格式的粘贴到 EditText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何从 AlertDialog 获取结果? 下一篇:如何使 android EditText 的高度小于默认值?

相关文章

最新文章