一个让TextView的文本中制定关键字高亮显示的工具类
在项目开发中很多地方需要让文本中某些关键字高亮显示,这样来说写个工具类是不是很好呢,嘿嘿是的。
package com.example.textkeyword;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
public class KeyWordUtil {
/**
* @param color 关键字颜色
* @param text 文本
* @param keyword 关键字
* @return
*/
public static SpannableString keyWordHighLighting(int color, String text,
String keyword) {
SpannableString s = new SpannableString(text);
Pattern p = Pattern.compile(keyword);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return s;
}
/**
* @param color 关键字颜色
* @param text 文本
* @param keyword 多个关键字
* @return
*/
public static SpannableString keyWordHighLighting(int color, String text,
String[] keyword) {
SpannableString s = new SpannableString(text);
for (int i = 0; i < keyword.length; i++) {
Pattern p = Pattern.compile(keyword[i]);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return s;
}
}