Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 874
Rahul Gupta Avatar asked Nov 06 '13 10:11

Rahul Gupta


2 Answers

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);
    }
like image 133
ramaral Avatar answered Oct 05 '22 21:10

ramaral


There is a very simple solution:

When you set the Spannable object to a TextView you use myTextView.setText(spannable); this adds your custom formatting of you assigned to the spannable.

In order to clear all the spans at once from the TextView use: myTextView.setText(spannable.toString());

Example

Spannable spannable = new SpannableString(myTextView.getText().toString());

spannable.setSpan(new ForegroundColorSpan(Color.RED), 8, 13,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 4, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new BackgroundColorSpan(Color.BLUE), 10, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new UnderlineSpan(), 7, 11, 0);
myTextView.setText(spannable); // add all the spannable format
myTextView.setText(spannable.toString()); // clear all the spannable format
like image 34
Zain Avatar answered Oct 05 '22 23:10

Zain