SingaCpp
SingaCpp

Reputation: 125

How to remove span style from SpannableString

I was trying to remove style from my SpannableString but unfortunately is not working, my aim is to remove the style when I click on the text.

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

onClick Action :

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

Upvotes: 9

Views: 6494

Answers (2)

Zain
Zain

Reputation: 40840

As Zheng Xingjie pointed out you can remove a particular span with removeSpan() but you need to store the span object.

However, I came across a case that I need to remove a group of the same style spans anonymously, and leave other styles, So I did it by iterating on this particular type of spans as follows:

In my case, it was BackgroundColorSpan, but I will use StyleSpan like it had been asked:

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

Kotlin

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)

Upvotes: 8

Zheng Xingjie
Zheng Xingjie

Reputation: 106

Two styleSpan you new is not the same object. You can use a non-anonymous object to point it. Change your code like that:

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

onClick Action:

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

Upvotes: 7

Related Questions