Skip to content Skip to sidebar Skip to footer

Spannablestring Regex In A Listview

I have a ListView that I'm binding a collection of strings to, using a custom adapter. I'm also underlining certain keywords in the text. I'm using a SpannableString and a regula

Solution 1:

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)
{
  finalSpannableStringcontent=newSpannableString(text);

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

    Matcherm= Pattern.compile(sb.toString()).matcher(text);

    while (m.find())
    {
      content.setSpan(newUnderlineSpan(), 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.

Post a Comment for "Spannablestring Regex In A Listview"