2015-05-29 37 views
4

使用SDK 20+的手機認爲任何兩個單詞之間的點是一個鏈接。我怎樣才能製作我自己的鏈接探測器?安卓自動化過於激進

android:autoLink="web"認爲abra.kadabra是一個網址。

setAutoLinkMask(Linkify.WEB_URLS);認爲abra.kadabra是一個網址。

帶有SDK的電話< 20正確鏈接所有內容,錯誤僅在SDK爲20+時發生。什麼,我已經試過

例子:

代碼我自定義的TextView

SpannableString ss = new SpannableString(this.getText().toString());  
//LinkManager is a copy of Linkify but with another pattern.  
LinkManager.addLinks(ss, LinkManager.WEB_URLS); 
setText(ss);    
setMovementMethod(LinkMovementMethod.getInstance()); 
setWebLinksTouchFeedback(); 

這並沒有什麼linkify內部發生。即使當我使用Linkify而不是LinkManager

我已經嘗試了許多其他解決方案,所有這些解決方案最終都沒有鏈接任何東西或一切。那裏有任何解決方案?

+0

事情是,'abra.kadabra'很可能是一個網址(今天不是。)。現在有一堆TLD。 – njzk2

回答

3

您可以使用MatcherPattern類別製作自己的鏈接檢測器,並使它們可點擊ClickableSpan

String text = textView.getText().toString(); 

int i=0; 
SpannableString spannableString = new SpannableString(text); 
Matcher urlMatcher = Patterns.WEB_URL.matcher(text); 
while(urlMatcher.find()) { 
    String url = urlMatcher.group(i); 
    int start = urlMatcher.start(i); 
    int end = urlMatcher.end(i++); 
    spannableString.setSpan(new GoToURLSpan(url), start, end, 0); 
} 

textView.setText(spannableString); 
textView.setMovementMethod(new LinkMovementMethod());  

private static class GoToURLSpan extends ClickableSpan { 
    String url; 

    public GoToURLSpan(String url){ 
     this.url = url; 
    } 

    public void onClick(View view) { 
     Uri webPage = Uri.parse(url); //http:<URL> or https:<URL> 
     Intent intent = new Intent(Intent.ACTION_VIEW, webPage); 
     view.getContext().startActivity(intent); 
    } 
} 

<TextView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/text" 
    android:text="Link http://google.com but dont link abra.kadabra" 
    android:textColorLink="@color/accent" 
    android:textColorHighlight="@color/accent" /> 

替換Pattern.WEB_URL用你自己的。你可以在StackOverflow中找到一些url模式。

0

我自己通過在setText的super方法之前調用這個方法來解決它,因爲我想鏈接的所有文本都是動態設置的。

private void linkifyTexts(CharSequence charsequence) 
{ 
    String text = charsequence.toString(); 
    String[] parts = text.split("\\s+"); 
    for (int i = 0; i < parts.length; i++) 
    { 
     boolean isUrl = isURLValid(parts[i]); 
     if (isUrl) 
     { 
      setAutoLinkMask(Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); 
      setWebLinksTouchFeedback(); 
      break; 
     } 
    } 
} 

public boolean isURLValid(String url) 
{ 
    Pattern p = Pattern.compile(getContext().getString(R.string.url_pattern)); 
    return p.matcher(url).matches(); 
} 

帶有我想要接受的網址的自定義模式。感謝您的幫助,我很感激。