0

假设您有以下字符串:
“https://google.com to go to google. https://amazon.com to go to Amazon”。

在 TextView 中,您如何将 url 替换为显示“单击此处”(或西班牙语中的“Haz clic aquí”)的链接,并将您带到正确的 url?

请记住,文本是动态的,它是从 API 中检索的,并且无法知道任何给定帖子中是否或有多少链接。

成品应如下所示:
“<a href="https://google.com" rel="nofollow noreferrer">点击此处前往 google。 点击此处前往亚马逊。”</p>

4

1 回答 1

0

经过许多小时……</p>

这是我的解决方案。我把这段代码放在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());
于 2022-02-22T11:55:58.920 回答