如何在 textview 中制作所有 3 种类型的链接 [英] How to make all 3 types of links in textview

查看:23
本文介绍了如何在 textview 中制作所有 3 种类型的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使 textview 中的所有链接都可点击.

I woduld like to make all of links in textview clickable.

示例文本为:

"All three should link out http://google.com  and <a href="http://google.com">here link</a> and <a href="http://google.com">http://google.com</a>"

如果我将 MovementMethod 与 html 文本一起使用,则只有第二个和第三个链接可点击.如果我使用 Linkify(或混合使用),则只有第一个和第二个链接是可点击的.

If I use MovementMethod with the html text, only second and third link is clickable. If I use Linkify(or mix both) only first and second link is clickable.

我怎样才能让它们都可以点击?

How can I make all of them clickable?

推荐答案

经过调查,我发现 Linkify.addLinks() 方法从文本中删除当前跨度并应用新的一次(基于例如网页 url).因此,我从 Html.fromHtml() 的跨度在开始时被删除,再也不会应用.

After invesigation I found that Linkify.addLinks() method remove current spans from text and apply new once (based on eg web page url). Because of that my spans from Html.fromHtml() was deleted at the beginning and never applay again.

所以我做了以下:
1. 从 htmml Html.fromHtml 读取文本,它给了我带有 html spans 的 Spanned obj.
2. 将 html 中的 spans 保存在数组中
3. 制作 linkify.addLinks - 此方法删除我的旧跨度,因此我必须将其添加回来
4. 添加旧跨度
5. 将文本设置为文本视图.

So I did following:
1. Read thext from htmml Html.fromHtml which gives me Spanned obj with html spans.
2. Save spans from html in array
3. Make linkify.addLinks - this method remove my old spans so I will have to add it back
4. Add old spans
5. Set text to the textview.

实施:

private void setLabel(){    
    label.setText(linkifyHTML(Html.fromHtml("text with links here"));
    label.setMovementMethod(LinkMovementMethod.getInstance());
    label.setLinkTextColor(getRes().getColor(R.color.link));
}
    private Spannable linkifyHTML(CharSequence text) {
        Spannable s = new SpannableString(text);

        URLSpan[] old = s.getSpans(0, s.length(), URLSpan.class);
        LinkSpec oldLinks[] = new LinkSpec[old.length];

        for (int i = 0; i < old.length; i++) {
            oldLinks[i] = new LinkSpec(old[i], s.getSpanStart(old[i]), s.getSpanEnd(old[i]));
        }

       Linkify.addLinks(s, Linkify.ALL);
       for (LinkSpec span : oldLinks) {
           s.setSpan(span.span, span.start, span.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
       }
       return s;
    }

    class LinkSpec {
        final URLSpan span;
        final int start, end;

        public LinkSpec(URLSpan urlSpan, int spanStart, int spanEnd) {
            span = urlSpan;
            start = spanStart;
            end = spanEnd;
        }
    }

这篇关于如何在 textview 中制作所有 3 种类型的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆