如果不需要点击事件,只是想实现部分文字变色的话
第一步:实现目标文字段点击事件
final SpannableStringBuilder style = new SpannableStringBuilder();
String content = "文章内容"
String trim = "#" + "目标文字" + "#";
//设置文字
style.append(trim+content);
//设置部分文字点击事件
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
MyContext.startActivity(new Intent(MyContext, Activity_topic.class));
}
};
style.setSpan(clickableSpan, 0, trim.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
第二步:去除下划线
这边有一个要点:
必须要先去除下划线,再给文字设置颜色,否则颜色无效. // 也就是说,必须一步两步三步按顺序去做,勿要搞错顺序!
//去除下划线,写在第一步代码的下面:
NoUnderlineSpan noUnderlineSpan = new NoUnderlineSpan();
style.setSpan(noUnderlineSpan,0 , trim.length(), Spanned.SPAN_MARK_MARK);
// 创建一个自定义的去除下划线的 Span 内部类或者外部类,自行选择
class NoUnderlineSpan extends UnderlineSpan {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
}
}
第三步:定义目标文字(超链接)的颜色
//设置部分文字颜色
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
style.setSpan(foregroundColorSpan, 0, trim.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//经历三步处理后,最终配置给TextView
MyTextView.setMovementMethod(LinkMovementMethod.getInstance());
MyTextView.setText(style);