Skip to content Skip to sidebar Skip to footer

How To Make All 3 Types Of Links In Textview

I woduld like to make all of links in textview clickable. The example text is: 'All three should link out http://google.com and here link

Solution 1:

After invesigation I found that Linkify.addLinks() method remove current spans from text and apply new once (based on eg web page url). Because of that my spans from Html.fromHtml() was deleted at the beginning and never applay again.

So I did following: 1. Read thext from htmml Html.fromHtml which gives me Spanned obj with html spans. 2. Save spans from html in array 3. Make linkify.addLinks - this method remove my old spans so I will have to add it back 4. Add old spans 5. Set text to the textview.

Implementation:

privatevoidsetLabel(){    
    label.setText(linkifyHTML(Html.fromHtml("text with links here"));
    label.setMovementMethod(LinkMovementMethod.getInstance());
    label.setLinkTextColor(getRes().getColor(R.color.link));
}
    private Spannable linkifyHTML(CharSequence text) {
        Spannables=newSpannableString(text);

        URLSpan[] old = s.getSpans(0, s.length(), URLSpan.class);
        LinkSpec oldLinks[] = newLinkSpec[old.length];

        for (inti=0; i < old.length; i++) {
            oldLinks[i] = newLinkSpec(old[i], s.getSpanStart(old[i]), s.getSpanEnd(old[i]));
        }

       Linkify.addLinks(s, Linkify.ALL);
       for (LinkSpec span : oldLinks) {
           s.setSpan(span.span, span.start, span.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
       }
       return s;
    }

    classLinkSpec {
        final URLSpan span;
        finalint start, end;

        publicLinkSpec(URLSpan urlSpan, int spanStart, int spanEnd) {
            span = urlSpan;
            start = spanStart;
            end = spanEnd;
        }
    }

Solution 2:

You have to use the backslash \ to scape " character so the string will not consider it as the final point of the string. I mean, a string is considered when all the text is inside two "". You have to scape " characters in your url because if not the string will consider that it has to end when he find a new " character, in this case in your url.

"All three should link out http://google.com  and <ahref=\"http://google.com\">here link</a> and <ahref=\"http://google.com\">http://google.com</a>"

Post a Comment for "How To Make All 3 Types Of Links In Textview"