I'm using an EditText control that I allow text formatting of (bold, italics etc.).
To apply formatting, within my TextWatcher's AfterTextChanged event handler I detect whether a formatting style, such as bold, has been toggled on via the UI. If it is, I've tried two different approaches, neither of which are satisfactory for different reasons:
Approach 1
textView.EditableText.SetSpan(new StyleSpan(TypefaceStyle.Bold), start, end, SpanTypes.ExclusiveExclusive);
For the start value, I've tried using _textView.SelectionStart - 1 or the starting position when the StyleSpan was first applied. And for the end value _textView.SelectionStart.
Although the text appears formatted fine using this method, it creates unnecessary StyleSpans when only the single would suffice. This is clear when I try to save the text to my local db through a Html conversion:
string html = Html.ToHtml(new SpannableString(Fragment_Textarea.Instance().Textarea().EditableText));
For example, instead of <b>this is bold text</b>
, I'm getting <b><b><b><b><b><b><b><b><b><b><b><b><b><b><b><b><b>this is bold text</b></b></b></b></b></b></b></b></b></b></b></b></b></b></b></b></b>
. So, clearly, I'm doing something wrong/being inefficient in this approach. What obviously this leads to is eventual slowdowns when both inputting text as well as retrieving at launch.
Something I've considered is to check whether there's a Span on the preceding character (_textView.SelectionStart - 1
), and, if yes, to remove the span, and then add a span that starts at that point up until _textView.SelectionStart
i.e. ensures there's only a single Span by constantly checking/removing/adding the necessary Span. But this seems like another inefficient method to handle this.
Approach 2
textView.EditableText.SetSpan(new StyleSpan(TypefaceStyle.Bold), start, end, SpanTypes.ExclusiveInclusive);
So, this doesn't lead to the same inefficiencies as above, but because of the SpanTypes.ExclusiveInclusive
flag, I'm unable to stop the style formatting to end when I toggle it off via the UI. In other words, when I toggle the Bold style on, all text that follows will be formatted in bold styling, even when I've turned its toggle off.
Of the two, this seems to me like the one that's the correct general approach, and so I'm wondering whether I can do anything to stop the style being applied as soon as I turn its toggle off. Or is there another way that I've missed altogether as best practice for handling this sort of requirement.