使用Linkify查找和设置文本内的链接时,处理对TextView链接的单击 [英] Handle clicks on TextView's links while using Linkify for finding and setting the links inside the text

查看:94
本文介绍了使用Linkify查找和设置文本内的链接时,处理对TextView链接的单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextView,其中填充了我从服务器获取的文本.我正在使用 Linkify 来处理所有链接搜索和在整个addLinks方法中需要的地方设置URLSpan.

i have a TextView filled with text which i get from a server. I'm using Linkify for handling all the link searching and for setting a URLSpan where needed throughout its addLinks method.

问题是单击链接时的默认行为是在浏览器中打开它,我想要的是获取被单击的链接并自行处理.

The problem is that the default behavior when clicking a link is opening it in a browser, what i want is to get the clicked link and handle it my self.

我没有看到Linkify的任何方法让我设置"OnClick"之类的东西...

I don't see any method of Linkify which let me set a "OnClick" or something...

感谢您的帮助:)

推荐答案

好,所以我终于设法将自己的"OnClickListener"设置为TextView的链接. 我的解决方案是将Linkify复制到我的项目中,将其命名为CustomLinkify,然后更改其applyLink方法:

Ok so i finally managed to set my own "OnClickListener" to the TextView's links. My solution was to copy Linkify to my project, name it CustomLinkify and just change its applyLink method:

发件人:

private static final void applyLink(String url, int start, int end, Spannable text) 
{
    URLSpan span = new URLSpan(url);

    text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

收件人:

private static final void applyLink(final String url, int start, int end, Spannable text) 
{
    URLSpan span = new URLSpan(url)
    {
        @Override
        public void onClick(View widget)
        {
            _onLinkClickListener.onLinkClicked(url);
        }
    };

    text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

_onLinkClickListener是新字段,由我在使用新的CustomLinkify之前设置.

Where _onLinkClickListener is a new field, set by me before using the new CustomLinkify.

我知道这不是一个非常优雅的解决方案,我更喜欢Google允许通过本机Linkify设置侦听器,但是对我来说,这比实现我自己的Spannable逻辑要好(如其他相关问题所建议).

I know its not a very elegant solution and i prefered google to allow setting a listener through the native Linkify, but, for me, this is better than implementing my own Spannable logics (as suggested in other related questions).

我相信Linkify代码,我想我会不时检查它是否有任何更改,如果是的话,我当然会用这些更改来更新CustomLinkify.

I trust the Linkify code and i guess i'll check from time to time to see if any changes made on it, if so, i'll of course update CustomLinkify with the changes.

希望这会对某人有所帮助.

Hope this will help someone.

这篇关于使用Linkify查找和设置文本内的链接时,处理对TextView链接的单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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