Reputation: 9071
I'm adding a rich-text editing field to my app. I'm using a standard EditText field, and I've added a toolbar with some editing buttons that apply spans to the selected text. This part works fine.
When I change the text selection by tapping different parts of the EditText, I want my buttons to reflect the current state by highlighting if the selected text already matches that format. For example, if I tap in some bold text, the bold button should highlight. This part also works fine, with the following exception:
Sometimes as I'm editing text, Android adds an underline to a word, in the same color as the text color. This isn't the spelling error underline; I think it's meant to assist in selecting the word, but I'm not sure what its purpose is. The problem is that Android uses a Spannable to add this underline, which my underline button sees, and thinks the word has had the underline style applied to it, so my button activates when it shouldn't.
My button uses this code to see if the selected text is underlined:
if (text.getSpans(selStart, selEnd, UnderlineSpan.class).length > 0) {
isUnderlined = true;
}
I tried viewing the properties of the underline spans, but they are always the same for both kinds of spans:
for (UnderlineSpan span : text.getSpans(selStart, selEnd, UnderlineSpan.class)) {
Log.d("FormatToolbar", "found underline span: " + span.getUnderlying() + ", " + span.getSpanTypeId() + ", " + span.describeContents() + ", " + span.toString());
}
Is there any way to tell the difference between an underline span I added to my text, and the temporary span that Android adds as I select different parts of the text?
Upvotes: 0
Views: 161
Reputation: 9071
I ended up subclassing UnderlineSpan:
import android.text.style.UnderlineSpan;
public class MyUnderlineSpan extends UnderlineSpan {
// we need this to tell the difference between underlines we add and underlines that Android adds temporarily as we edit the text
}
Then I create my underline spans as instances of MyUnderlineSpan, and test for that when I'm checking the formatting of selected text:
for (UnderlineSpan span : text.getSpans(selStart, selEnd, UnderlineSpan.class)) {
if (span instanceof MyUnderlineSpan) {
isUnderlined = true;
break;
}
}
The subclass doesn't even need any properties, it's just a way to identify whether I created a span or Android did. Kind of silly, but it works.
Upvotes: 0