【问题标题】:Ignore one url in linkify忽略linkify中的一个url
【发布时间】:2016-06-13 10:43:03
【问题描述】:

我有一个文本视图,我目前与以下链接匹配:

Linkify.addLinks(holder.tvMessage, Linkify.ALL);

但是,现在我想匹配所有内容(电话号码、电子邮件、网址),除了一个特定的网址 http://dontmatch.com

我已经尝试过后续调用,例如:

    Linkify.addLinks(holder.tvMessage, Linkify.EMAIL_ADDRESSES);
    Linkify.addLinks(holder.tvMessage, Linkify.PHONE_NUMBERS);
    Linkify.addLinks(holder.tvMessage, Linkify.MAP_ADDRESSES);
    Linkify.addLinks(holder.tvMessage, pattern, "http://");

但似乎每次调用都会覆盖上一次调用的链接,而只留下最后一次调用的链接。我也不确定如何编写正则表达式以匹配除我希望忽略的站点之外的所有内容。我需要 MatchFilter 吗?

更新:

我可以过滤掉我不想要的网址:

Linkify.addLinks(holder.tvMessage, Patterns.WEB_URL, null, new MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence seq, int start, int end) {
                String url = seq.subSequence(start, end).toString();
                //Apply the default matcher too. This will remove any emails that matched.
                return !url.contains("dontmatch") && Linkify.sUrlMatchFilter.acceptMatch(seq, start, end);
            }
        }, null);

但我如何指定我还想要电子邮件、电话号码等?

【问题讨论】:

    标签: android linkify


    【解决方案1】:

    最后我是这样解决的,但我真的希望有更好的方法:

    private void linkifyView(TextView textview) {
    
        Linkify.addLinks(textview, Patterns.WEB_URL, null, new MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence seq, int start, int end) {
                String url = seq.subSequence(start, end).toString();
                //Apply the default matcher too. This will remove any emails that matched.
                return !url.contains(IGNORE_URL) && Linkify.sUrlMatchFilter.acceptMatch(seq, start, end);
            }
        }, null);
    
        //Linkify removes any existing spans when you call addLinks, and doesn't provide a way to specify multiple
        //patterns in the call with the MatchFilter. Therefore the only way I can see to add the links for
        //email phone etc is to add them in a separate span, and then merge them into one.
        SpannableString webLinks = new SpannableString(textview.getText());
        SpannableString extraLinks = new SpannableString(textview.getText());
    
        Linkify.addLinks(extraLinks, Linkify.MAP_ADDRESSES | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS);
    
        textview.setText(mergeUrlSpans(webLinks, extraLinks));
    }
    
    private SpannableString mergeUrlSpans(SpannableString span1, SpannableString span2) {
    
        URLSpan[] spans = span2.getSpans(0, span2.length() , URLSpan.class);
        for(URLSpan span : spans) {
            span1.setSpan(span, span2.getSpanStart(span), span2.getSpanEnd(span), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    
        return span1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多