美文网首页
Android中处理TextView带超链接HTML标签的点击事

Android中处理TextView带超链接HTML标签的点击事

作者: 耗子JF | 来源:发表于2017-03-27 15:18 被阅读0次

    主要的处理方法:

        /**
         * 格式化超链接文本内容并设置点击处理
         * */
        private CharSequence getClickableHtml(String html) {
            Spanned spannedHtml = Html.fromHtml(html);
            SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
            URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
            for(final URLSpan span : urls) {
                setLinkClickable(clickableHtmlBuilder, span);
            }
            return clickableHtmlBuilder;
        }
    
        /**
         * 设置点击超链接对应的处理内容
         * */
        private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,final URLSpan urlSpan) {
            int start = clickableHtmlBuilder.getSpanStart(urlSpan);
            int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
            int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
    
            ClickableSpan clickableSpan = new ClickableSpan() {
                public void onClick(View view) {
                    LogW.i("URL-click:"+urlSpan.getURL());
                }
            };
    
            clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
        }
    

    实际调用场景:

        //一串带超链接的文本内容
        String context = "这是一个测试内容<a herf='https:www.baidu.com'>点我跳转</a>";
        TextView textview = findviewById(R.id.textview);
        textview.setText(getClickableHtml(context  );
        //这一句很重要,否则ClickableSpan内的onClick方法将无法触发!!
        textview.setMovementMethod(LinkMovementMethod.getInstance());
    

    相关文章

      网友评论

          本文标题:Android中处理TextView带超链接HTML标签的点击事

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