Android EditText: how to apply spans when composing?

非 Y 不嫁゛ 提交于 2019-12-08 04:26:14

问题


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.


回答1:


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

  • How to set other types of spans
  • Meaning of the Spannable flags



回答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.



来源:https://stackoverflow.com/questions/26242210/android-edittext-how-to-apply-spans-when-composing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!