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

主要的处理方法:

    /**
     * 格式化超链接文本内容并设置点击处理
     * */
    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 = "这是一个测试内容点我跳转";
    TextView textview = findviewById(R.id.textview);
    textview.setText(getClickableHtml(context  );
    //这一句很重要,否则ClickableSpan内的onClick方法将无法触发!!
    textview.setMovementMethod(LinkMovementMethod.getInstance());

你可能感兴趣的:(Android中处理TextView带超链接HTML标签的点击事件处理方法)