简体   繁体   中英

Android Spanned getSpanEnd() returns wrong value

I am using Html.fromHtml to parse some html string, and then going through the spans, I am looking to find the start and end of each span. I noticed that for <a> tags the getSpanEnd returns the same value as start. Does anyone know how can I get the proper value? Thanks for any clue.

val spannedHtml = Html.fromHtml("The <b>quick</b> <span style='color:#a52a2a;'>brown</span> <i>fox</i> jumps <a>over</a> <u>the</u> <a>lazy dog</a>.", Html.FROM_HTML_MODE_LEGACY)
val spans: Array<Any> = spannedHtml.getSpans(0, spannedHtml.length - 1, Any::class.java)
spans.forEach { span ->
    val start = spannedHtml.getSpanStart(span)
    val end = spannedHtml.getSpanEnd(span)
    Log.d("span", "${span.javaClass.name} $start $end")
}

and this is the result:

android.text.style.StyleSpan 4 9
android.text.style.ForegroundColorSpan 10 15
android.text.style.StyleSpan 16 19
android.text.HtmlToSpannedConverter$Href 26 26
android.text.style.UnderlineSpan 31 34
android.text.HtmlToSpannedConverter$Href 35 35

as you can see, the getSpanEnd returns the same value as getSpanStart for HtmlToSpannedConverter$Href . does anyone have any idea why? thanks for any clue.

For Html.fromHtml the <a> element isn't a link ( URLSpan ) unless it has an href attribute. The valid form is <a href="url">link text </a> .

android.text.HtmlToSpannedConverter$Href 26 26

here HtmlToSpannedConverter$ Href is only marker object, not a real Span.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM