android 如何让文本中某个关键字高亮显示?

TextView tv = (TextView) findViewById(R.id.hello);
SpannableString s = new SpannableString(getResources().getString(R.string.linkify));

Pattern p = Pattern.compile("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);

/*******************************************************/
 
  1. SpannableStringBuilder style = new SpannableStringBuilder("test Height light");
  2. //参数一:高亮颜色[ForegroundColorSpan前景色]
  3. //from:高亮开始
  4. //to:高亮结束
  5. style.setSpan(new ForegroundColorSpan(color), from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  6. (TextView)view.setText(style);
 /*******************************************************/
可以使用以下两种方法来实现:

1.用Html类的fromHtml()方法格式化要放到TextView里的文字。这种方法不仅能够高亮部分文字,而且还能够使用HTML里面方式来格式化文字,显示出各种效果。

  1. TextView.setText(Html.fromHtml("<font color=#FF0000>hello</font>"));
 

上述代码把hello设置成红色。
2.使用Spannable或实现它的类,如SpannableString。Spannable对象也可以实现一样的效果

  1. SpannableString ss = new SpannableString("abcdefgh");
  2. ss.setSpan(new BackgroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  3. TextView.setText(ss);
 

上述代码把[2,4)之间的字符设置成红色,也就是c和d。

 
 
原文地址:https://www.cnblogs.com/cmblogs/p/4704724.html