Search code examples
androidspannablestring

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

Solution

  • 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