内置WebView打开TextView文本中的超链接
2022-06-16 本文已影响0人
next_discover
mTvContent.setMovementMethod(LinkMovementMethod.getInstance()); //这一句是关键
mTvContent.setText(setTextLinkOpenByWebView(getContext(),mContent));
public SpannableStringBuilder setTextLinkOpenByWebView(final Context context, String answerString) {
if (!TextUtils.isEmpty(answerString)) {
Spanned htmlString = Html.fromHtml(answerString);
if (htmlString instanceof SpannableStringBuilder) {
SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) htmlString;
// 取得与a标签相关的Span
Object[] objs = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), URLSpan.class);
if (null != objs && objs.length != 0) {
for (Object obj : objs) {
int start = spannableStringBuilder.getSpanStart(obj);
int end = spannableStringBuilder.getSpanEnd(obj);
if (obj instanceof URLSpan) {
//先移除这个Span,再新添加一个自己实现的Span。
URLSpan span = (URLSpan) obj;
final String url = span.getURL();
spannableStringBuilder.removeSpan(obj);
spannableStringBuilder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
WebViewActivity.startWebView(context,url,"");
}
}, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
return spannableStringBuilder;
}
}
return new SpannableStringBuilder(answerString);
}