Android EditText: how to apply spans when composin

2019-06-06 06:02发布

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条回答
混吃等死
2楼-- · 2019-06-06 06:30

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

查看更多
登录 后发表回答