Skip to content

Instantly share code, notes, and snippets.

@bulwinkel
Created January 12, 2017 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bulwinkel/c38f9cfa25f8edc7fbc37054d6caae0b to your computer and use it in GitHub Desktop.
Save bulwinkel/c38f9cfa25f8edc7fbc37054d6caae0b to your computer and use it in GitHub Desktop.
Android helper functions for highlighting a search term in a given CharSequence.
import android.support.annotation.ColorInt;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jetbrains.annotations.NotNull;
import static android.text.Spanned.SPAN_INCLUSIVE_EXCLUSIVE;
public class CharSequences {
@NotNull public static final Pattern SPACE = Pattern.compile("\\s");
private CharSequences() {
// no instances
}
/**
* Highlights the search term in the given color throughout the given text. If the search term
* consists of multiple words, each word is searched for and highlighted separately.
*
* @param searchTerm search term to highlight
* @param text text in which to highlight the search term
* @param colorInt highlight color
* @return the resulting text with highlights
*/
public static CharSequence highlightSearchTermInText(CharSequence searchTerm, CharSequence text, @ColorInt int colorInt) {
return highlightSearchTermInText(SPACE.split(searchTerm), text, colorInt);
}
@SuppressWarnings("ForLoopReplaceableByForEach")
public static CharSequence highlightSearchTermInText(CharSequence[] searchWords, CharSequence text, @ColorInt
int colorInt) {
final SpannableStringBuilder highlighted = new SpannableStringBuilder(text);
for (int i = 0; i < searchWords.length; i++) {
final CharSequence word = searchWords[i];
highlightSearchTermInText(word, highlighted, colorInt);
}
return highlighted;
}
public static SpannableStringBuilder highlightSearchTermInText(CharSequence searchWord, SpannableStringBuilder stringBuilder, @ColorInt int colorInt) {
if (searchWord.length() == 0) return stringBuilder;
final Pattern searchPattern = Pattern.compile(searchWord.toString(), Pattern.CASE_INSENSITIVE);
final Matcher matcher = searchPattern.matcher(stringBuilder);
while (matcher.find()) {
stringBuilder.setSpan(new ForegroundColorSpan(colorInt), matcher.start(0), matcher.end(0), SPAN_INCLUSIVE_EXCLUSIVE);
}
//Timber.d("spannableStringBuilder = %s", stringBuilder);
return stringBuilder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment