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

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


超文本.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 ,发现


image.png

URLSpan 继承 ClickableSpan这个类


image.png

    /**
     * Makes the text underlined and in the link color.
     */
    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(ds.linkColor);
        ds.setUnderlineText(true);
    }



这里updateDrawState方法是设置下划线的核心操作,我们可以自己写一个类继承URLSpan 设置不显示下划线


image.png

image.png

在设置完超链接过滤之后,重新设置一个Spannable 确实可以去掉下划线,也许你会以为,我去这也太简单了吧,但其实这里面的坑还有很多,
如果一个列表的item里不止一处需要过滤超文本,这样的做法就会有问题


image.png

重写updateDrawState方法虽然可以去掉下划线,但是会严重影响我们之前定义超文本的校验,也就是说之前过滤的文本内容会被重新设置一次,这是为什么呢,我们看一下源码和我们设置Spannable的区别
源码:


image.png

自定义的


image.png

这里的length长度是有问题的,他是全部文本的长度,但是我们怎么能拿到每次过滤之后超文本/超链接开始和结束的长度呢?
最简单的办法就是把源码拿过来,只改变URLSpan 里面的ds.setUnderlineText(false);设置为false
我们先把触发设置下划线的方法拿过来,addLinks 重载方法,相关的方法全部拿过来
 public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
                                      @Nullable String scheme, @Nullable Linkify.MatchFilter matchFilter,
                                      @Nullable Linkify.TransformFilter transformFilter) {
        addLinks(text, pattern, scheme, null, matchFilter, transformFilter);
    }

    public static void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
                                      @Nullable String defaultScheme, @Nullable String[] schemes,
                                      @Nullable Linkify.MatchFilter matchFilter, @Nullable Linkify.TransformFilter transformFilter) {
        SpannableString spannable = SpannableString.valueOf(text.getText());

        boolean linksAdded = addLinks(spannable, pattern, defaultScheme, schemes, matchFilter,
                transformFilter);
        if (linksAdded) {
            text.setText(spannable);
            addLinkMovementMethod(text);
        }
    }

    public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern,
                                         @Nullable  String defaultScheme, @Nullable String[] schemes,
                                         @Nullable Linkify.MatchFilter matchFilter, @Nullable Linkify.TransformFilter transformFilter) {
        final String[] schemesCopy;
        if (defaultScheme == null) defaultScheme = "";
        if (schemes == null || schemes.length < 1) {
            schemes = new String[]{};
        }

        schemesCopy = new String[schemes.length + 1];
        schemesCopy[0] = defaultScheme.toLowerCase(Locale.ROOT);
        for (int index = 0; index < schemes.length; index++) {
            String scheme = schemes[index];
            schemesCopy[index + 1] = (scheme == null) ? "" : scheme.toLowerCase(Locale.ROOT);
        }

        boolean hasMatches = false;
        Matcher m = pattern.matcher(spannable);

        while (m.find()) {
            int start = m.start();
            int end = m.end();
            boolean allowed = true;

            if (matchFilter != null) {
                allowed = matchFilter.acceptMatch(spannable, start, end);
            }

            if (allowed) {
                String url = makeUrl(m.group(0), schemesCopy, m, transformFilter);

                NoLineClickableSpan span = new NoLineClickableSpan(url);

                spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                hasMatches = true;
            }
        }

        return hasMatches;
    }

    private static final String makeUrl(@NonNull String url, @NonNull String[] prefixes,
                                        Matcher matcher, @Nullable Linkify.TransformFilter filter) {
        if (filter != null) {
            url = filter.transformUrl(matcher, url);
        }

        boolean hasPrefix = false;

        for (int i = 0; i < prefixes.length; i++) {
            if (url.regionMatches(true, 0, prefixes[i], 0, prefixes[i].length())) {
                hasPrefix = true;

                // Fix capitalization if necessary
                if (!url.regionMatches(false, 0, prefixes[i], 0, prefixes[i].length())) {
                    url = prefixes[i] + url.substring(prefixes[i].length());
                }

                break;
            }
        }

        if (!hasPrefix && prefixes.length > 0) {
            url = prefixes[0] + url;
        }

        return url;
    }

    private static final void addLinkMovementMethod(@NonNull TextView t) {
        MovementMethod m = t.getMovementMethod();

        if ((m == null) || !(m instanceof LinkMovementMethod)) {
            if (t.getLinksClickable()) {
                t.setMovementMethod(LinkMovementMethod.getInstance());
            }
        }
    }
image.png

注意这里换成我们自定义的Span,然后重新设置的spanable就会保留之前的正则过滤并且干掉下划线
下面贴上完整工具类,亲测可用:

public class CircleUtils {

    /**
     * 设置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);

        final String targetId = getTagData(tv);
        Pattern pattern0 = Pattern.compile("\\#.*?\\#");
        String scheme0 = String.format("%s/?%s=", "lcsdevdiv://sina_lcs_profile_", "targetid");
        addLinks(tv, pattern0, scheme0, new Linkify.MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence s, int start, int end) {
                if(!TextUtils.isEmpty(targetId)) {
                    //如果有观点链接,肯定是拼在最前面
                    if(start == 0) {
                        return true;
                    }
                }
                return false;
            }
        }, new Linkify.TransformFilter() {
            @Override
            public String transformUrl(Matcher match, String url) {
                return targetId;
            }
        });

        Pattern pattern = Pattern.compile("\\$[^$]+?(sh|sz|gn|hy|dy)[A-Z]?[A-Z]?[0-9]{6}\\)?\\$");
        String scheme1 = String.format("%s/?%s=", "lcsdevdiv://sina_lcs_profile_", "keyword");
        addLinks(tv, pattern, scheme1, null, new Linkify.TransformFilter() {
            @Override
            public String transformUrl(Matcher match, String url) {
                String keyword = url.substring(1, match.group(0).length());
                Matcher m = Pattern.compile("\\(.*\\)").matcher(keyword);
                if (m.find()) {
                    keyword = m.group(0);
                    keyword = keyword.replaceAll("\\(", "");
                    keyword = keyword.replaceAll("\\)", "");
                }
                return keyword;
            }
        });

        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);
            }
        });

    }

    private static String getTagData(TextView view) {
        String result = "";
        try {
            Object object = view.getTag();
            if(object != null) {
                result = object.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
                                      @Nullable String scheme, @Nullable Linkify.MatchFilter matchFilter,
                                      @Nullable Linkify.TransformFilter transformFilter) {
        addLinks(text, pattern, scheme, null, matchFilter, transformFilter);
    }

    public static void addLinks(@NonNull TextView text, @NonNull Pattern pattern,
                                      @Nullable String defaultScheme, @Nullable String[] schemes,
                                      @Nullable Linkify.MatchFilter matchFilter, @Nullable Linkify.TransformFilter transformFilter) {
        SpannableString spannable = SpannableString.valueOf(text.getText());

        boolean linksAdded = addLinks(spannable, pattern, defaultScheme, schemes, matchFilter,
                transformFilter);
        if (linksAdded) {
            text.setText(spannable);
            addLinkMovementMethod(text);
        }
    }

    public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern,
                                         @Nullable  String defaultScheme, @Nullable String[] schemes,
                                         @Nullable Linkify.MatchFilter matchFilter, @Nullable Linkify.TransformFilter transformFilter) {
        final String[] schemesCopy;
        if (defaultScheme == null) defaultScheme = "";
        if (schemes == null || schemes.length < 1) {
            schemes = new String[]{};
        }

        schemesCopy = new String[schemes.length + 1];
        schemesCopy[0] = defaultScheme.toLowerCase(Locale.ROOT);
        for (int index = 0; index < schemes.length; index++) {
            String scheme = schemes[index];
            schemesCopy[index + 1] = (scheme == null) ? "" : scheme.toLowerCase(Locale.ROOT);
        }

        boolean hasMatches = false;
        Matcher m = pattern.matcher(spannable);

        while (m.find()) {
            int start = m.start();
            int end = m.end();
            boolean allowed = true;

            if (matchFilter != null) {
                allowed = matchFilter.acceptMatch(spannable, start, end);
            }

            if (allowed) {
                String url = makeUrl(m.group(0), schemesCopy, m, transformFilter);

                NoLineClickableSpan span = new NoLineClickableSpan(url);

                spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                hasMatches = true;
            }
        }

        return hasMatches;
    }

    private static final String makeUrl(@NonNull String url, @NonNull String[] prefixes,
                                        Matcher matcher, @Nullable Linkify.TransformFilter filter) {
        if (filter != null) {
            url = filter.transformUrl(matcher, url);
        }

        boolean hasPrefix = false;

        for (int i = 0; i < prefixes.length; i++) {
            if (url.regionMatches(true, 0, prefixes[i], 0, prefixes[i].length())) {
                hasPrefix = true;

                // Fix capitalization if necessary
                if (!url.regionMatches(false, 0, prefixes[i], 0, prefixes[i].length())) {
                    url = prefixes[i] + url.substring(prefixes[i].length());
                }

                break;
            }
        }

        if (!hasPrefix && prefixes.length > 0) {
            url = prefixes[0] + url;
        }

        return url;
    }

    private static final void addLinkMovementMethod(@NonNull TextView t) {
        MovementMethod m = t.getMovementMethod();

        if ((m == null) || !(m instanceof LinkMovementMethod)) {
            if (t.getLinksClickable()) {
                t.setMovementMethod(LinkMovementMethod.getInstance());
            }
        }
    }

}

你可能感兴趣的:(android去掉超文本、超链接的下划线——终极解决方案)