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
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With