Android Edittext-清除跨度

发布于 2025-01-08 13:39:27 字数 205 浏览 5 评论 0原文

我试图通过调用 EditText.getText().clearSpans() 来清除其跨度。但是,如果我调用此方法,EditText 就会开始表现得很奇怪,换行符显示为框,然后我设置的任何跨度都位于完全错误的位置。

所以我的问题是:如何清除 EditText 中的跨度? (如果不调用 setText() - 文本可能有数千行长,并且频繁重绘它太慢)

非常感谢!

I am trying to get an EditText to clear its spans by calling EditText.getText().clearSpans(). However, if I call this method, the EditText starts to behave strangely, with line feeds appearing as boxes and any spans I then set being in completely the wrong place.

So my question is: How do I clear spans from and EditText? (Without calling setText()- the text may be thousands of lines long and its too slow to redraw it all frequently)

Thanks very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奈何桥上唱咆哮 2025-01-15 13:39:27

有同样的问题。通过仅删除我添加到 EditText 的跨度类型解决了这个问题。我猜clearSpans 删除的内容超出了应有的范围。我对我使用的每种类型的跨度做了类似的事情:

toRemoveSpans = et.getSpans(0, et.getText().length(), ForegroundColorSpan.class);
for (int i = 0; i < toRemoveSpans.length; i++) 
    et.removeSpan(toRemoveSpans[i]);

Had the same problem. Solved it by removing only the types of spans that I added to the EditText. I guess clearSpans removes more than it should. I did something like this for each type of span I used:

toRemoveSpans = et.getSpans(0, et.getText().length(), ForegroundColorSpan.class);
for (int i = 0; i < toRemoveSpans.length; i++) 
    et.removeSpan(toRemoveSpans[i]);
秋风の叶未落 2025-01-15 13:39:27
private void clearSpans(@NonNull final Editable editable) {
    final Object[] spans = editable.getSpans(0, editable.length(), Object.class);
    for (final Object span : spans) {
        if (span instanceof ForegroundColorSpan || span instanceof SpannableTextView.CustomTypefaceSpan) {
            editable.removeSpan(span);
        }
    }
}

根据您添加的跨度类型,您可能需要包含的不仅仅是 ForegroundColorSpan。上述方法是简单的替换,并且很容易指定要删除的跨度。

private void clearSpans(@NonNull final Editable editable) {
    final Object[] spans = editable.getSpans(0, editable.length(), Object.class);
    for (final Object span : spans) {
        if (span instanceof ForegroundColorSpan || span instanceof SpannableTextView.CustomTypefaceSpan) {
            editable.removeSpan(span);
        }
    }
}

Depending on type of spans you have added you may have to include more than just ForegroundColorSpan. The above method is a simple drop in replacement and it easy to specify what spans to remove.

悲喜皆因你 2025-01-15 13:39:27

最好的答案是“s”是您想要显示的字符串而不是跨度,或者它可以是空字符串。

代码位于Kotlin

editText.setText(s)
editText.setSelection(editText.text.length)

the best answer would be this which "s" is the string that you want to show instead of spans or it can be empty String.

the code is in Kotlin

editText.setText(s)
editText.setSelection(editText.text.length)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文