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);
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);
}
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
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