2016-06-13 36 views
1

一個網址我有我目前匹配的鏈接一個TextView:忽略linkify

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

不過,現在我想匹配的一切(PHONENUMBERS,電子郵件,網址),除了一個particulat網址,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); 

但是我怎麼指定我也想了電子郵件,電話號碼等?

回答

2

最後我解決了它這樣的,但我真的希望有一個更好的辦法:

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