Dynamically replace url's with custom text hyperlink url in Android TextView

552 views Asked by At

Let’s say you have the string:
"https://google.com to go to google. https://amazon.com to go to Amazon."

In a TextView, how would you replace the url’s with a link that shows “Click here” (or “Haz clic aquí” in spanish) and would take you to the correct url?

Keep in mind that the text is dynamic, it’s retrieved from the API, and there is no way to know if or how many links may be in any given post.

The finished product should look like this:
Click here to go to google. Click here to go to Amazon.”

1

There are 1 answers

2
Avramo On

After many many hours…

Here is my solution. I put this code inside the RecyclerView adapter's onBindViewHolder().

 // replace url links with clickable link that says "Click here" (or "Haz clic aquí" in Spanish).
 // link color is set in TextView in the xml.  

 // SpannableStringBuilder is mutable, so we can replace the link.
 SpannableStringBuilder spannableStringBuilder = new 
 SpannableStringBuilder(newsFeedItem.getBody());
 
 // use Linkify to automatically set all Url's in the string.
 Linkify.addLinks(spannableStringBuilder,Linkify.WEB_URLS);  
 
 //do this process for each Url
 for (URLSpan urlSpan: spannableStringBuilder.getSpans(0,spannableStringBuilder.length(),URLSpan.class)){
    int start = spannableStringBuilder.getSpanStart(urlSpan);
    int end = spannableStringBuilder.getSpanEnd(urlSpan);  
    // put whatever you want it to say into the next line where I wrote "Click here".
    SpannableString customLinkSpannableString = new SpannableString("Click here");
    customLinkSpannableString.setSpan(urlSpan,0, customLinkSpannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableStringBuilder.replace(start, end, customLinkSpannableString);
 }

 // now set the fixed up string into the TextView and set LinkMovementMethod.
 textView.setText(spannableStringBuilder);
 textView.setMovementMethod(LinkMovementMethod.getInstance());