-
SpannableStringBuilder style=newSpannableStringBuilder("test
Height light");
-
//参数一:高亮颜色[ForegroundColorSpan前景色]
-
//from:高亮开始
-
//to:高亮结束
-
style.setSpan(newForegroundColorSpan(color),from,
to,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- (TextView)view.setText(style);
可以使用以下两种方法来实现:
1.用Html类的fromHtml()方法格式化要放到TextView里的文字。这种方法不仅能够高亮部分文字,而且还能够使用HTML里面方式来格式化文字,显示出各种效果。
上述代码把hello设置成红色。
2.使用Spannable或实现它的类,如SpannableString。Spannable对象也可以实现一样的效果
- SpannableString ss = new SpannableString("abcdefgh");
- ss.setSpan(new BackgroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- TextView.setText(ss);
上述代码把[2,4)之间的字符设置成红色,也就是c和d。