SpannableString regex in a ListView

守給你的承諾、 提交于 2019-12-01 01:12:19

You are creating a lot of Patterns and Matchers you don't need. I suggest you create one regex to match all the keywords, like this:

private SpannableString Highlight(String text, List<Keyword> keywords)
{
  final SpannableString content = new SpannableString(text);

  if (keywords.size() > 0)
  {
    /* create a regex of the form: \b(?:word1|word2|word3)\b */
    StringBuilder sb = ne StringBuilder("\\b(?:").append(keywords.get(0).toString());
    for (int i = 1; i < keywords.size(); i++)
    {
      sb.append("|").append(keywords.get(i).toString());
    }
    sb.append(")\\b");

    Matcher m = Pattern.compile(sb.toString()).matcher(text);

    while (m.find())
    {
      content.setSpan(new UnderlineSpan(), m.start(), m.end(), 0);
    }
  }

  return content;
}

Pattern objects are quite expensive to create, so that's where your real savings will come from. On the other hand, Matchers are relatively cheap, which is why I switched from using a static instance to creating a new one each time.

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