Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 583
SingaCpp Avatar asked Nov 05 '15 02:11

SingaCpp


People also ask

What is Spanned text in Android?

Spans are powerful markup objects that you can use to style text at a character or paragraph level. By attaching spans to text objects, you can change text in a variety of ways, including adding color, making the text clickable, scaling the text size, and drawing text in a customized way.

What is layout span in Android?

Stretching layout using Layout SpansThe amount of space given to each element, is specified in the android:layout_span attribute, which tells us how many columns it will span over.

How to use span in Android?

Apply a span by calling setSpan(Object what, int start, int end, int flags) on the Spannable object. The what Object is the marker that will be applied from a start to an end index in the text.


2 Answers

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
like image 142
Zheng Xingjie Avatar answered Sep 26 '22 19:09

Zheng Xingjie


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)
like image 43
Zain Avatar answered Sep 22 '22 19:09

Zain