美文网首页
内置WebView打开TextView文本中的超链接

内置WebView打开TextView文本中的超链接

作者: next_discover | 来源:发表于2022-06-16 21:55 被阅读0次
     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);
        }
    
    

    相关文章

      网友评论

          本文标题:内置WebView打开TextView文本中的超链接

          本文链接:https://www.haomeiwen.com/subject/tuzqvrtx.html