Using Linkify.addLinks combine with Html.fromHtml

后端 未结 3 2201
暖寄归人
暖寄归人 2021-02-14 19:16

I have a TextView that gets it\'s data set by calling this:

tv.setText(Html.fromHtml(myText));

The string myText cont

相关标签:
3条回答
  • 2021-02-14 19:46

    You can try this one:

    First set the text in to your TextView.

    tv.setText(myText);
    

    Convert the links with Linkify

    Linkify.addLinks(tv, Linkify.ALL);
    

    and finally replace the text with Html.fromHtml but using the Linkified text from your EditText.

    tv.setText(Html.fromHtml(tv.getText().toString()));
    
    0 讨论(0)
  • 2021-02-14 19:53

    It's because Html.fromHtml and Linkify.addLinks removes previous spans before processing the text.

    Use this code to get it work:

    public static Spannable linkifyHtml(String html, int linkifyMask) {
        Spanned text = Html.fromHtml(html);
        URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
    
        SpannableString buffer = new SpannableString(text);
        Linkify.addLinks(buffer, linkifyMask);
    
        for (URLSpan span : currentSpans) {
            int end = text.getSpanEnd(span);
            int start = text.getSpanStart(span);
            buffer.setSpan(span, start, end, 0);
        }
        return buffer;
    }
    
    0 讨论(0)
  • 2021-02-14 20:02

    100% works solution (kotlin).

    Create class for store HtmlLink before Linkify

    class HtmlLink(val urlSpan: URLSpan, val spanStart: Int, val spanEnd: Int)
    

    Create spanned html (both formats for test)

    val spanned = Html.fromHtml("https://google.com" +
                    "<br><a href=\"https://google.com\">Google</a>")
    

    Store html

    val htmlLinks = ArrayList<HtmlLink>()
    spanned.getSpans(0, spanned.length, URLSpan::class.java).forEach { urlSpan ->
        htmlLinks.add(HtmlLink(urlSpan, 
                      spanned.getSpanStart(urlSpan),
                      spanned.getSpanEnd(urlSpan)))
    }
    

    Create spannable builder and Linkify it

    val builder = SpannableString(spanned)
    Linkify.addLinks(builder, Linkify.WEB_URLS)
    

    Restore spans.

    htmlLinks.forEach { htmlLink ->
        builder.setSpan(URLSpan(htmlLink.urlSpan.url), htmlLink.spanStart, htmlLink.spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    

    Set finally text

    scrollContent.text = builder
    
    0 讨论(0)
提交回复
热议问题