0

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 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this code! It saved me many, many hours of work. You da man, Avramo!
My pleasure to share! I'm happy this helped someone else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.