問題描述
如果我從 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模板網!