Android- getSpans()始终返回长度为0的数组

时间:2016-12-15 11:42:02

标签: android spannablestring

这让我发疯了:

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 matt@google.com should become links to.
    Or email mailto links such as mailto:matt@google.com 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.我在这里做错了什么,如何解析String中的所有url?

编辑:Html.fromHtml(message)代替message参数返回相同的结果。

2 个答案:

答案 0 :(得分: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 matt@google.com should become links to.
      Or email mailto links such as mailto:matt@google.com should become links to.
      And of course lets not forget querstryings such as http://mattheworiordan.com/?test-param=true_or_false" 

将产生1。如果您不想使用Html,则必须以编程方式设置URLSpan

答案 1 :(得分:1)

简单错误。在调用getSpans之前尝试调用Linkify.addLinks