How to clear formatting of a Spannable Text, including last character?

Rahul Gupta picture Rahul Gupta · Nov 6, 2013 · Viewed 8.4k times · Source

I am using this code to remove formatting of a spannable text from start till end. The problem is that it is working successfully, but the last character in the text is still bold (or italics/underline).

removeSpan is not working on the last character in the text:

int startSelection = 0;
int endSelection = text.length();
if(startSelection > endSelection) {
    startSelection  = text.getSelectionEnd();
    endSelection = text.getSelectionStart();
}

Spannable str = text.getText();
StyleSpan[] ss = str.getSpans(startSelection, endSelection, StyleSpan.class);
for (int i = 0; i < ss.length; i++) {
    if (ss[i].getStyle() == android.graphics.Typeface.BOLD) {
        str.removeSpan(ss[i]);
    }
    if (ss[i].getStyle() == android.graphics.Typeface.ITALIC) {
        str.removeSpan(ss[i]);
    }
}

UnderlineSpan[] ulSpan = str.getSpans(startSelection, endSelection, UnderlineSpan.class);
for (int i = 0; i < ulSpan.length; i++) {
    str.removeSpan(ulSpan[i]);
}

str.removeSpan(ss[1]);

text.setText(str);

Answer

ramaral picture ramaral · Nov 7, 2013

If you want remove all spans from text use this:

Spannable str = text.getText();    
Object spansToRemove[] = str.getSpans(startSelection, endSelection, Object.class);
    for(Object span: spansToRemove){
        if(span instanceof CharacterStyle)
            spannable.removeSpan(span);
    }