最近在开发中遇到一个问题:搜索关键字的同时,搜索框下方对应显示搜索结果,同时在每项搜索结果中高亮显示关键字。这里对如何高亮显示关键字进行一下简单的总结:
1. 用Html类的fromHtml()方法
textView.setText(Html.fromHtml("<font color=#FF0000>hello</font>"));
显示结果为:hello
2.使用Spannable或实现它的类
SpannableString s = new SpannableString("This is my teacher.");
s.setSpan(new ForegroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView.setText(s);
显示结果为:This is my teacher.
3.方法二中适合 关键字位置已知 的情况,那么在不清楚关键字位置的情况下,要借助于Pattern类和Matcher类
SpannableString s = new SpannableString(sourceStr);
Pattern p = Pattern.compile("abc");//这里的abc为关键字
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s);
显示结果为: 当sourceStr为abcdefghigklmn时,显示为abcdefghigklmn ; 当sourceStr为mmmmabcdefghigklmn时,显示为mmmmabcdefghigklmn.