简体   繁体   English

在 Android TextView 中用自定义文本超链接动态替换 url url

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

Let's say you have the string:假设您有以下字符串:
"https://google.com to go to google. https://amazon.com to go to Amazon." “https://google.com 至 go 至谷歌。https://amazon.com至 go 至亚马逊。”

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?在 TextView 中,您如何将 url 替换为显示“单击此处”(或西班牙语中的“Haz clic aquí”)的链接并将您带到正确的 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.请记住,文本是动态的,它是从 API 中检索到的,并且无法知道任何给定帖子中是否有链接或有多少链接。

The finished product should look like this:成品应该是这样的:
Click here to go to google. 点击此处拨打 go 到 google。 Click here to go to Amazon.”点击此处拨打 go 转至亚马逊。”

After many many hours…许多小时后……

Here is my solution.这是我的解决方案。 I put this code inside the RecyclerView adapter's onBindViewHolder() .我将此代码放在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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM