4

How can I apply spans on EditText text when the user is composing?

For example the user has activated "bold" when composing, so every character input since then should be bold.

I thought about adding text change listener to the EditText and update the text as the user composes, but I wanna know if there's a better way of doing this.

user3705007
  • 265
  • 4
  • 12
  • you dont need anything: for example set bold span with length of 3, then place the caret inside it and start typing... – pskink Oct 07 '14 at 18:15
  • @pskink - But what if there's no text at all ? – user3705007 Oct 07 '14 at 18:17
  • hint: try different setSpan's flags – pskink Oct 07 '14 at 18:21
  • @pskink I have tried different flags but unfortunately with no luck. – user3705007 Oct 07 '14 at 18:43
  • what flags did you try? – pskink Oct 07 '14 at 18:55
  • @pskink Okay I figured it out (I think), well at first it didn't matter which flag I used because the style was incorrect. I used just android.graphics.Typeface.BOLD instead of StyleSpan(android.graphics.Typeface.BOLD). After fixing that I started playing with flags again and eventually found one that works, which is Spannable.SPAN_INCLUSIVE_INCLUSIVE. – user3705007 Oct 07 '14 at 19:06

2 Answers2

2

The question was already answered in the comments, but to make it more permanent I will add a fuller answer.

In order to set a span (like Bold) wherever the user is composing, you just set a span on the text at the cursor (or selection) position.

StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
int flag = Spannable.SPAN_INCLUSIVE_INCLUSIVE;
editText.getText().setSpan(boldSpan, start, end, flag);

The SPAN_INCLUSIVE_INCLUSIVE flag means that any text added before or after the span will be included in the span, even if the text length is 0 when the span is added.

See also

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    Thank you for the great suggestion. The flag 'SPAN_INCLUSIVE_INCLUSIVE' setting font BOLD works well. But, when I switch to set the font NOT BOLD(just return to normal), the text insertted is still BOLD. So how to resolve this problem. Thank you! – Gallery Mar 15 '18 at 07:39
  • Have a look at [`clearSpans()`](https://developer.android.com/reference/android/text/Editable.html#clearSpans()) and [`removeSpan()`](https://developer.android.com/reference/android/text/Spannable.html#removeSpan(java.lang.Object)). @Gallery – Suragch Mar 15 '18 at 10:54
2

You can use the text watcher, and set the span in the editable that you receive in the afterTextChanged() method, I'm currently writing a rich text editor and this is the approach I've used with styles, and it works quite well, however, so far I haven't been able to set the spans that requires the paragraphs like quoteSpan, or bulletSpan.

But if you just want simple styles like italics, or bold etc., you can use this approach.

ejderuby
  • 710
  • 5
  • 21