2016-12-15 132 views
1

這已經快把我逼瘋了:Android- getSpans()總是返回長度的數組0

String message = "Here is some example test with URLs from mattheworiordan.com. 
    Any of the URLs which are prefixed with www. should become URLs such as www.mattheworiordan.com/path_name.html 
    And an explicit URL such as http://www.mattheworiordan.com/ should become a URL. 
    Emails such as [email protected] should become links to. 
    Or email mailto links such as mailto:[email protected] should become links to. 
    And of course lets not forget querstryings such as http://mattheworiordan.com/?test-param=true_or_false" 

    SpannableString spannable = new SpannableString(message); 
    URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class); 
    Linkify.addLinks(spannable, Linkify.ALL); 
    Log.v("data_", "length:" + Integer.toString(spans.length)); 

的URLSpan []數組的長度始終爲0。什麼我錯在這裏做什麼,怎麼能我解析字符串中的所有網址?

編輯:Html.fromHtml(消息)代替消息參數返回相同的結果。

+0

它只是文本,你沒有任何跨度的文字 – Blackbelt

回答

2

這是因爲你沒有任何跨度。在Html.fromHtml的情況下得到URLSpan,您必須使用標籤<a href。例如。

String message = "Here is some example test with URLs from mattheworiordan.com. 
     Any of the URLs which are prefixed with www. should become URLs such as www.mattheworiordan.com/path_name.html 
     And an explicit URL such as <a href='http://www.mattheworiordan.com/'>http://www.mattheworiordan.com/</a> should become a URL. 
     Emails such as [email protected] should become links to. 
     Or email mailto links such as mailto:[email protected] should become links to. 
     And of course lets not forget querstryings such as http://mattheworiordan.com/?test-param=true_or_false" 

將產生1。如果你不想使用Html,那麼你將不得不通過編程設置URLSpan s

0

簡單的錯誤。嘗試調用Linkify.addLinks 之前調用getSpans。

+0

請用一些代碼回答。 –