import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
/**
* 设置文本关键字高亮处理
* @param text 文本内容
* @param keyword 关键字
* @param textView 控件
*/
private void setHighLineText(String text,String keyword,TextView textView) {
if (!TextUtils.isEmpty(keyword) && !TextUtils.isEmpty(text)) {
if (text.toLowerCase().contains(keyword.toLowerCase())){
int start = 0;
if (text.contains(keyword)){
start = text.indexOf(keyword);
}else {
start = text.toLowerCase().indexOf(keyword.toLowerCase());
}
SpannableStringBuilder styled = new SpannableStringBuilder(text);
styled.setSpan(new ForegroundColorSpan(Color.RED), start, start + keyword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(styled);
}else {
textView.setText(text);
}
}
}
优化了因为关键字中掺杂大小写字母 不匹配的问题