2013-03-11 56 views
1

我具有例如以下字符串的TextView與多個超鏈接

\ N 3門下來是一個http://www.last.fm/tag/post-grunge \ 「類= \」 bbcode_tag \ (吉他),Matt Roberts(吉他),Todd Harrell(貝司),Chris Henderson(吉他)組成的1996年成立的美國密西西比州Escatawpa的後搖滾樂隊, ,以及Greg Upchurch(鼓樂隊)。樂隊於2000年與Universal Records簽約,爲他們的第一張專輯,http://www.last.fm/music/3+Doors+Down/The+Better+Life \「class = \」 bbcode_album \「>更美好的生活。他們獲得了國際上的關注,發行了單曲" http://www.last.fm/music/3+Doors+Down/_/Kryptonite \「class = \」bbcode_track \「> Kryptonite "。專輯接着發行出售超過600萬份。\ n \ n http://www.last.fm/music/3+Doors+Down\">在Last.fm上閱讀關於3門的更多內容\ n \ n \ n用戶提供的文本是根據Creative Commons by-SA許可證提供的,也可以在GNU FDL下提供。\ n

我想在超文本鏈接中點擊顯示整個字符串。我也不想看到實際的網址,只是顯示網址的文字。關於這個問題的閱讀其他職位,他們都建議定義與此類似

<TextView 
      android:id="@+id/tvArtistOverview" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_margin="10dp" 
      android:autoLink="web" 
      android:linksClickable="true" /> 

一個TextView和TextView中的SetMovementMethod設置爲

myTextView.setMovementMethod(LinkMovementMethod.getInstance()); 

當我按照這些步驟,我的鏈接是可以點擊的,但他們沒有按照我的意願顯示。我錯過了什麼?

下面是它目前的樣子。

nearly there

回答

0

使用下面的代碼。

TextView tv = .... 
tv.setMovementMethod(LinkMovementMethod.getInstance()); 

    String content = tv.getText().toString(); 
    List<String> links = new ArrayList<String>(); 

    Pattern p = Patterns.WEB_URL; 
    Matcher m = p.matcher(content); 
    while (m.find()) { 
     String urlStr = m.group(); 
     links.add(urlStr); 
    } 

    SpannableString f = new SpannableString(content); 

    for (int i = 0; i < links.size(); i++) { 
     final String url = links.get(i); 

     f.setSpan(new InternalURLSpan(new OnClickListener() { 
      public void onClick(View v) { 
       Context ctx = v.getContext(); 
       String urlToOpen = url; 
       if (!urlToOpen.startsWith("http://") || !urlToOpen.startsWith("https://")) 
        urlToOpen = "http://" + urlToOpen; 
       openURLInBrowser(urlToOpen, ctx); 
      } 
     }), content.indexOf(url), content.indexOf(url) + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
    } 

    tv.setText(f); 
+0

不幸的是,似乎並沒有從超鏈接中清除網址。它們仍然以內聯方式顯示。 InternalURLSpan是ClickableSpan的一個擴展類,除了事件處理程序覆蓋以外沒有其他任何內容? – Redshirt 2013-03-11 05:47:19