android去掉超文本、超链接的下划线——终极解决方案

在开发中,有时需要对文本之中的超链接或者类似于微博#话题#这样特殊文本进行过滤,包括特殊字符的点击事件,以及颜色处理,比如这样超文本.jpg这样的需求可以用原生的Linkify类来处理,下面是一个用来过滤http://或者https的链接写法,通过我们自己写的正则表达式来过滤超文本,然后原生的Linkify会给符合我们定义的规则(例如微博#话题#
摘要由CSDN通过智能技术生成

在开发中,有时需要对文本之中的超链接或者类似于微博#话题#这样特殊文本进行过滤,包括特殊字符的点击事件,以及颜色处理,比如这样


超文本.jpg

这样的需求可以用原生的Linkify类来处理,下面是一个用来过滤http://或者https的链接写法,通过我们自己写的正则表达式来过滤超文本,然后原生的Linkify会给符合我们定义的规则(例如微博#话题#)改变颜色,并且点击可以特殊处理,与正常点击recyclerview或者lsitview条目跳转不同

/**
     * 设置textview里面链接点击后跳转
     *
     * @param itemView 点击文字时,若点击区域不是链接, 
默认是哪个view响应点击事件,通常情况就是listView或recyclerView的itemView
     */
  public static void setURLClickEvent(final TextView tv, final View itemView) {
        String text = tv.getText().toString();
        if (!text.contains("http://") && !text.contains("https://") && !text.contains("ftp://") && !text.contains("$") && !text.contains("#")) {
            tv.setMovementMethod(null);
            return;
        }
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setAutoLinkMask(0);
        tv.setLinksClickable(true);
        
        String scheme2 = String.format("%s/?%s=", "lcsdevdiv://sina_lcs_profile_", "uid");
        tv.setLinkTextColor(FrameworkApp.getInstance().getResources().getColor(R.color.color_lcs_blue_pressed));
        Pattern pattern2 = 
        Pattern.compile("((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)");
        addLinks(tv, pattern2, scheme2, null, new Linkify.TransformFilter() {
            @Override
            public String transformUrl(Matcher match, String url) {
                return URLEncoder.encode(url);
            }
        });
}

但是如何改变超文本的颜色呢?Textview已经提供了原生的方法


image.png
tv.setLinkTextColor(FrameworkApp.getInstance().getResources().getColor(R.color.color_lcs_blue_pressed));

但是如果挑剔的设计师想要去掉原生的下划线,怎么办,原生的Textview并没有提供修改下划线的方法
我们先去看看源码,在Linkify这个类中475行


image.png
    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);
    }

看到这个私有的添加链接的方法,然后找到找到URLSpan ,发现


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值