textview自定义跳转链接
设置方式 ,主要是遍历html中的url,然后加一个自定义的跳转
private void setTextLink(String rule) { if(TextUtils.isEmpty(rule)){ return; } mTips.setText(Html.fromHtml(rule)); mTips.setMovementMethod(LinkMovementMethod.getInstance()); CharSequence text = mTips.getText(); if (text instanceof Spannable) { int end = text.length(); Spannable spannable = (Spannable) mTips.getText(); URLSpan[] urlSpans = spannable.getSpans(0, end, URLSpan.class); if (urlSpans.length == 0) { return; } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text); spannableStringBuilder.clearSpans();//注意,必须先清除默认span,否则不会生效 // 循环遍历并拦截 所有http://开头的链接 for (URLSpan uri : urlSpans) { String url = uri.getURL(); if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) { CustomUrlSpan customUrlSpan = new CustomUrlSpan(getActivity(),url); spannableStringBuilder.setSpan(customUrlSpan, spannable.getSpanStart(uri), spannable.getSpanEnd(uri), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } } mTips.setText(spannableStringBuilder); } }
自定义的span
public class CustomUrlSpan extends ClickableSpan { private Context context; private String url; public CustomUrlSpan(Context context,String url){ this.context = context; this.url = url; } @Override public void onClick(View widget) {
//TODO 自定的跳转写这里 } }