我有一个textview,其中可以包含https://www.google.com等链接和带锚标记的超链接Google
现在,我在此textview上添加了以下属性。
Linkify.addLinks(textview, Linkify.WEB_URLS);
textview.setMovementMethod(LinkMovementMethod.getInstance());
但像https://www.google.com这样的链接以蓝色显示并重定向到页面但锚标签不是蓝色的,它们不会重定向。
所以,我想让我的textview呈现两种类型的链接:直接链接和超链接。我怎么能这样做。
答案 0 :(得分:0)
Linkify
(你调用它的方式)只知道转换实际上看起来像网址的东西(即它们以http或https开头,后跟冒号和两个斜线等等)
如果您想将其他内容转换为链接,则必须向Linkify
添加更多参数,以便更灵活地转换您想要的内容。您可以创建MatchFilter和TransformFilter,然后调用Linkify.addLinks(TextView text, Pattern p, String scheme, Linkify.MatchFilter matchFilter, Linkify.TransformFilter transformFilter)
但在我看来,你想要像#34; Google"并添加" https://www.google.com"的链接。那不是可以扫描的东西。为此,您需要使用SpannableStringBuilder
。您的代码可能如下所示:
String text = "This is a line with Google in it.";
Spannable spannable = new SpannableString(text);
int start = text.indexOf("Google");
int end = start + "Google".length();
URLSpan urlSpan = new URLSpan("https://www.google.com");
spannable.setSpan(urlSpan, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(spannable);
答案 1 :(得分:0)
在Linkify#addLinks(Spannable, Int)
的{{3}}中提到:
...如果掩码非零,它还会删除附加到Spannable的任何现有URLSpans,以避免在同一文本上重复调用它时出现问题。
虽然您使用的Linkify#addLinks(TextView, Int)
中未提及,但它们似乎遵循相同的行为,并且在链接之前将删除现有链接(即您问题中的“锚标记”)。
要解决方法并保留现有链接(在您的情况下为“锚标记”),您需要备份现有的跨度(即TextView#getText
- >转换为跨区 - >使用Spanned#getSpans
列出现有链接 - >使用Spanned#getSpanStart
和Spanned#getSpanEnd
以及Spanned#getSpanFlags
检索每个链接的设置
在linkify之后,重新添加跨度(即TextView#getText
- >转换为Spannable
- >使用Spannable#setSpan
重新添加链接 - >设置Spannable
返回TextView#setText
)
根据您的情况,您可能还需要检查重叠的“锚标记”和“链接链接”并进行相应调整...
如您所见,这是非常繁琐且复杂且容易出错的代码。为简化起见,我将所有这些内容合并到javadoc库中以供重用和共享。使用Textoo,您可以通过以下方式实现相同目标:
TextView myTextView = Textoo
.config((TextView) findViewById(R.id.view_location_disabled))
.linkifyWebUrls()
.apply();
Textoo将保留现有链接并链接所有不重叠的网址。
答案 2 :(得分:0)
//the string to add links to
val htmlString = "This has anchors and urls http://google.com also <a href=\"http://google.com\">Google</a>."
//Initial span from HtmlCompat will link anchor tags
val htmlSpan = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_LEGACY) as Spannable
//save anchor links for later
val anchorTagSpans = htmlSpan.getSpans(0, htmlSpan.length, URLSpan::class.java)
//add first span to TextView
textView.text = htmlSpan
//Linkify will now make urls clickable but overwrite our anchor links
Linkify.addLinks(textView, Linkify.ALL)
textView.movementMethod = LinkMovementMethod.getInstance()
textView.linksClickable = true
//we will add back the anchor links here
val restoreAnchorsSpan = SpannableString(textView.text)
for (span in anchorTagSpans) {
restoreAnchorsSpan.setSpan(span, htmlSpan.getSpanStart(span), htmlSpan.getSpanEnd(span), Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
//all done, set it to the textView
textView.text = restoreAnchorsSpan