如何从 SpannableString 中删除跨度样式

How to remove span style from SpannableString

我试图从 SpannableString 中删除样式,但不幸的是没有用,我的目标是在单击文本时删除样式。

SpannableString content = new SpannableString("Test Text");
content.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, content.length(), 0);
...

点击操作:

content.removeSpan(new StyleSpan(Typeface.BOLD_ITALIC)) // not working

你新建的两个styleSpan不是同一个对象。您可以使用非匿名对象来指向它。像这样更改您的代码:

StyleSpan styleSpan = new StyleSpan(Typeface.BOLD_ITALIC); content.setSpan(styleSpan , 0, content.length(), 0);

点击操作:

content.removeSpan(styleSpan);
textView.setText(content);// to redraw the TextView

正如郑兴杰指出的那样,您可以使用 removeSpan() 删除特定的跨度,但您需要存储跨度对象。

但是,我遇到了一个案例,我需要匿名删除一组相同样式的跨度,并保留其他样式,所以我通过迭代这种特定类型的跨度来实现,如下所示:

在我的例子中,它是 BackgroundColorSpan,但我会像被问到的那样使用 StyleSpan

Java

SpannableString content = new SpannableString("Test Text");
content.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, content.length(), 0);
StyleSpan[] spans = content.getSpans(0, content.length(), StyleSpan.class);
for (StyleSpan styleSpan: spans) content.removeSpan(styleSpan);
textview.setText(content);

科特林

val content = SpannableString("Test Text")
content.setSpan(StyleSpan(Typeface.BOLD_ITALIC), 0, content.length, 0)
val spans = content.getSpans(0, content.length, StyleSpan::class.java)
for (styleSpan in spans) content.removeSpan(styleSpan)
textview.setText(content)