首先在string.xml创建对应字串
<string name="link">我已仔细阅读并同意<annotation value="privacy_policy">《隐私政策》</annotation>和<annotation value="service_agreement">《服务协议》</annotation></string>
然后在java代码中初始化Checkbox
private void initCheckBox() {
CheckBox checkBox = findViewById(R.id.cb);
SpannableStringBuilder sb = new SpannableStringBuilder(getText(R.string.link));
Annotation[] annotations = sb.getSpans(
0, sb.length(), Annotation.class);
for (Annotation annotation : annotations) {
String annotationValue = annotation.getValue();
if (annotationValue.equals(USER_AGREEMENT) || annotationValue.equals(PRIVACY_AGREEMENT)) {
int start = sb.getSpanStart(annotation);
int end = sb.getSpanEnd(annotation);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
String url = "https:www.baidu.com";
switch (annotationValue) {
case USER_AGREEMENT:
url = "https:www.baidu.com";
break;google
case PRIVACY_AGREEMENT:
url = "https:www.google.com";
break;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "*/*");
startActivity(intent);
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.BLUE);
ds.setUnderlineText(true);
}
};
sb.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
checkBox.setText(sb);
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
}

拓展—从聊天信息中解析链接
private void initLinkText() {
TextView tvLink = findViewById(R.id.tv_link);
String linkStr = "跳转百度https://www.baidu.com或者跳转google https://www.google.com";
SpannableStringBuilder urlSpannableStringBuilder = createdUrlSpannableStringBuilder(linkStr);
tvLink.setText(urlSpannableStringBuilder);
tvLink.setLinkTextColor(Color.BLUE);
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
}
public SpannableStringBuilder createdUrlSpannableStringBuilder(String linkStr){
Matcher m = Pattern.compile("(((https|http)?://)?([a-z0-9]+[.])|(www.))"
+ "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)").matcher(linkStr);
SpannableStringBuilder sb = new SpannableStringBuilder(linkStr);
while(m.find()){
String url = m.group();
URLSpan urlSpan = new URLSpan(url);
sb.setSpan(urlSpan,m.start(),m.end(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return sb;
}
