1.核心类:
public class MyTextView extends android.support.v7.widget.AppCompatTextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setSpecifiedTextsColor(String text, String specifiedTexts, int color) {
List<Integer> sTextsStartList = new ArrayList<>();
int sTextLength = specifiedTexts.length();
String temp = text;
int lengthFront = 0;//记录被找出后前面的字段的长度
int start = -1;
do {
start = temp.indexOf(specifiedTexts);
if (start != -1) {
start = start + lengthFront;
sTextsStartList.add(start);
lengthFront = start + sTextLength;
temp = text.substring(lengthFront);
}
} while (start != -1);
SpannableStringBuilder styledText = new SpannableStringBuilder(text);
for (Integer i : sTextsStartList) {
styledText.setSpan(
new ForegroundColorSpan(color),
i,
i + sTextLength,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//这个一定要记得设置,不然点击不生效
setMovementMethod(LinkMovementMethod.getInstance());
styledText.setSpan(new TextClick(), i, i + sTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(styledText);
}
private class TextClick extends ClickableSpan {
@Override
public void onClick(View widget) {
//在此处理点击事件
Log.e("------->", "点击了");
// widget.seth
}
}
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(true);
}
}
2.调用
MyTextView tv = (MyTextView) findViewById(R.id.tv);
Pattern pattern = Pattern.compile("[1-9]\\d*[TBU][1-9]\\d*");
String code = "";
// 匹配短信内容
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
code = matcher.group(0);
}
tv = (MyTextView) findViewById(R.id.tv);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setSpecifiedTextsColor(text, "全球", Color.parseColor("#FF0000"));
tv.setHighlightColor(getResources().getColor(android.R.color.transparent));//设置点击后的颜色