user1132897
user1132897

Reputation: 1201

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.

Upvotes: 8

Views: 2938

Answers (3)

gmazzo
gmazzo

Reputation: 1265

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;
}

Upvotes: 8

wnafee
wnafee

Reputation: 2136

In your TextView's xml layout, you should add the following:

android:autoLink="all"
android:linksClickable="true"

Then you should remove your Linkify code in Java.

It works somehow, but I dont know why. I added a question to see if someone can explain the behavior: Using Linkify.addLinks combine with Html.fromHtml

Upvotes: 0

Tomas Vondracek
Tomas Vondracek

Reputation: 143

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

textView.setMovementMethod(LinkMovementMethod.getInstance());

Upvotes: 1

Related Questions