Suraj's answer 很棒并且可以工作,但是缺少 2 个组件。首先,它不会突出显示第一个单词(如Rany 评论的那样),其次,它不会忽略大小写,因此在此字符串中搜索"test":"This is a Test" 将找不到任何内容。
这是我更新的答案,它通过传递的参数解决了这两个问题,并且还添加了 alpha,以防您想使用自定义颜色进行突出显示。请注意,重载的第一个方法是一个示例,说明如何返回前一个方法所做的操作,而不是选择第一个项目。
/**
* Use this method to get the same return as the previous method
*/
public static SpannableString buildHighlightString(String originalText, String textToHighlight){
return buildHighlightString(originalText, textToHighlight, false, Color.YELLOW, 1.0F);
}
/**
* Build a spannable String for use in highlighting text colors
*
* @param originalText The original text that is being highlighted
* @param textToHighlight The text / query that determines what to highlight
* @param ignoreCase Whether or not to ignore case. If true, will ignore and "test" will have
* the same return as "TEST". If false, will return an item as highlighted
* only if it matches it case specficic.
* @param highlightColor The highlight color to use. IE {@link Color#YELLOW} || {@link Color#BLUE}
* @param colorAlpha Alpha to adjust how transparent the color is. 1.0 means it looks exactly
* as it should normally where as 0.0 means it is completely transparent and
* see-through. 0.5 means it is 50% transparent. Useful for darker colors
*/
public static SpannableString buildHighlightString(String originalText, String textToHighlight,
boolean ignoreCase, @ColorInt int highlightColor,
@FloatRange(from = 0.0, to = 1.0) float colorAlpha){
SpannableString spannableString = new SpannableString(originalText);
if (TextUtils.isEmpty(originalText) || TextUtils.isEmpty(textToHighlight)) {
return spannableString;
}
String lowercaseOriginalString = originalText.toLowerCase();
String lowercaseTextToHighlight = textToHighlight.toLowerCase();
if(colorAlpha < 1){
highlightColor = ColorUtils.setAlphaComponent(highlightColor, ((int)(255*colorAlpha)));
}
//Get the previous spans and remove them
BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span: backgroundSpans) {
spannableString.removeSpan(span);
}
//Search for all occurrences of the keyword in the string
int indexOfKeyword = (ignoreCase)
? lowercaseOriginalString.indexOf(lowercaseTextToHighlight)
: originalText.indexOf(textToHighlight);
while (indexOfKeyword != -1) {
//Create a background color span on the keyword
spannableString.setSpan(new BackgroundColorSpan(highlightColor), indexOfKeyword,
indexOfKeyword + (textToHighlight.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//Get the next index of the keyword
indexOfKeyword = (ignoreCase)
? lowercaseOriginalString.indexOf(lowercaseTextToHighlight, (indexOfKeyword) + textToHighlight.length())
: originalText.indexOf(textToHighlight, (indexOfKeyword) + textToHighlight.length());
}
return spannableString;
}