2012-06-04 104 views
1

我在TextView中有一個字符串,我想從該字符串中鏈接一個子字符串。例如:在TextView中鏈接一些文本

請點擊這裏瞭解更多信息。

我正在動態獲取字符串。所以我必須搜索,如果它有點擊這裏並將其轉換爲鏈接。如何鏈接「點擊此處」。

回答

2

要查找文本中的模式和替換它,使用:

Pattern p = Pattern.compile("click here"); 
Matcher m = p.matcher("for more info, click here"); 
StringBuffer sb = new StringBuffer(); 
boolean result = m.find(); 
while(result) { 
    m.appendReplacement(sb, "<a href=\"www.mywebsite.com\">click here</a>"); 
    result = m.find(); 
} 
m.appendTail(sb); 
String strWithLink = sb.toString(); 

yourTextView.setText(Html.fromHtml(strWithLink)); 
yourTextView.setMovementMethod(LinkMovementMethod.getInstance()) 

此代碼將您的字符串中搜索和替換所有「點擊這裏」的鏈接。

最後,不要將android:autoLink =「web」添加到您的XML資源(部分TextView),否則A標籤無法正確呈現並且無法再單擊。

+0

點擊此處正在被替換爲「click here」,而不是鏈接。 – Rookie

+0

我編輯了代碼,再次檢查。 –

+0

此代碼將用鏈接取代所有出現的「點擊此處」。 –

1

沒有你試過這樣

<a href="www.mywebsite.com">Click here</a> 

設置它的TextView

//得到這個直通supstring

String whatever="anything dynamically";        
String desc = "what you want to do is<a href='http://www.mysite.com/'>"+whatever+":</a>"; 


yourtext_view.setText(Html.fromHtml(desc)); 
+0

我應該在哪寫這個? – Rookie

+0

我明確提到了yourtext_view.setText。 –

+0

我正在動態獲取字符串。所以我想搜索一下,如果我有「點擊這裏」的字符串,然後將其轉換爲鏈接。 – Rookie

1
String urlink = "http://www.google.com"; 
String link = "<a href=\"+urlink+ >link</a>"; 
textView.setText(Html.fromHtml(link)); 
+0

我不知道在哪裏字符串,這將被鏈接,將是..所以我不能使用這種方法 – Rookie

+0

檢查更新回答 –

1

拉哈夫具有使用fromHtml正確的方法()方法,但是如果您正在搜索固定長度的字符串,則您c烏爾德這樣做:

String toFind = "click here"; 
if(myString.indexOf(toFind) > -1){ 
    String changed = myString.substring(0, myString.indexOf(toFind)) + "<a href='http://url.whatever'>" + myString.substring(myString.indexOf(toFind), myString.indexOf(toFind) + toFind.length()) + "</a>" + myString.substring(myString.indexOf(toFind) + toFind.length()); 
} 
else { 
    //String doesn't contain it 
} 

當設置的實際文本,你需要使用:tv.setText(Html.fromHtml(yourText));否則它只會顯示爲沒有任何添加劑的字符串。 fromHtml()方法允許您在應用程序中使用特定的HTML標籤。在這種情況下,用於鏈接的標籤。

+0

點擊這裏被替換爲「click here」,而不是通過鏈接。 – Rookie

+0

我也需要這樣做,textView.setText(HTML> fromHTML(已更改)); .. ?? – Rookie

+0

設置實際文本時,需要使用:tv.setText(Html.fromHtml(yourText));否則它只會顯示爲沒有任何添加劑的字符串。 fromHtml()方法允許您在應用程序中使用特定的HTML標籤。在這種情況下,用於鏈接的標籤。 - 編輯我的帖子與這 – Guardanis