Paste without rich text formatting into EditText(不带富文本格式的粘贴到 EditText)
问题描述
如果我从 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.
有没有办法告诉 EditText 视图忽略富文本格式?或者我可以在粘贴事件设置之前将其删除吗?我该怎么做?
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不带富文本格式的粘贴到 EditText
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01