Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process textview for HTML and Linkify

I am trying to get a textview to process a hyperlink as well as phone numbers. Say my text is:

"555-555-555, www.google.com, <a href="www.google.com">Google!</a>"

If I run Html.fromHtml() on this string, then the TextView shows Google! correctly as a clickable link but not the other two.

If I run Linkify.addLinks(TextView, Linkify.All) on the TextView, then the first two are correctly recognized as a phone number and url, but the html is not processed in the last one.

If I run both of them, then either one or the other is honored, but not both at the same time. (Html.fromHtml will remove the html tags there, but it won't be a link if linkify is called after)

Any ideas on how to get both of these functions to work simultaneously? So all the links are processed correctly? Thanks!

Edit: Also, the text is changed dynamically so I'm not sure how I would be able to go about setting up a Linkify pattern for that.

like image 840
user1132897 Avatar asked Oct 30 '12 15:10

user1132897


2 Answers

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;
}
like image 168
gmazzo Avatar answered Nov 18 '22 17:11

gmazzo


try to set movement method on your textview instead of using Linkify:

textView.setMovementMethod(LinkMovementMethod.getInstance());
like image 28
Tomas Vondracek Avatar answered Nov 18 '22 15:11

Tomas Vondracek