Android TextView format multiple words

梦想的初衷 提交于 2019-12-04 13:34:35

Pass different object for each span:

spannableStringBuilder.setSpan(c, start, end, 0);

You're passing the same object for each span:

new ForegroundColorSpan(0xFF0099FF)

When span object exists in spannableStringBuilder then it changes bounds only, not a new span is added.

I would suggest a simpler way. If your formatting needs are basic, a simple regex + Html.fromHtml() should do the trick:

private void format() {
    String mText = editContent.getText();

    Spanned mSpannedText = Html.fromHtml(mText.replaceAll("##(.*?)##)","<font color=\"0xFF0099\">#$1</font>"), 

    editContent.setText(mSpannedText);
}

The final solution correctly loops however your first token will not be correctly deleted as you have used

int start = text.toString().indexOf(token) + 1;

which would only work if your token was 1 character in length. Since your chosen token is ## change the above code to utilise the already created variable tokenLen

int start = text.toString().indexOf(token) + tokenLen;

this will ensure your text is correctly edited and all trace of your tokens are removed.

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