【问题标题】:Linkify click text and go to web urlLinkify 点击文本并转到网址
【发布时间】:2026-01-16 00:25:01
【问题描述】:

当用户点击时,它应该打开网络浏览器并转到https://www.google.com。但是 textView 的文本应该是“点击此处查看站点”。

    textView.text = "Click here for the site"
    val pattern = Pattern.compile("Click here for the site")
    val scheme = "https://www.google.com"
    Linkify.addLinks(textView, pattern, scheme)

如何用 Linkify 做到这一点?

此解决方案不起作用:Android: Linkify TextView

AndroidManifest:

<uses-permission android:name="android.permission.INTERNET" />

【问题讨论】:

标签: android linkify


【解决方案1】:

首先,我认为您拥有的scheme 值不正确(请参阅documentation of the 3 parameter addLinks method for more)。它应该只是 URL 方案,而不是整个 URL。所以,在你的例子中,那将是:

val scheme = "https"

尽管这可能仍然无法满足您的需求,因为https://Click here for the site 不会去任何地方。您可能需要添加TransformFilter 并调用5 parameter addLinks method。类似于(未经测试,因此语法可能已关闭):

Linkify.addLinks(
    textView,
    pattern,
    null, // scheme
    null, // matchFilter
    new Linkify.TransformFilter() {
        public String transformUrl(Matcher match, String url) {
            return "https://google.com"
        }
    }
)

这基本上就是您所说的Android: Linkify TextView 中的内容在您的情况下不起作用。因此,最后或者可能首先,您可能需要添加以下一行或两行:

textView.setLinksClickable(true)
textView.setMovementMethod(LinkMovementMethod.getInstance())

请参阅setLinksClickablesetMovementMethod 上的文档。

有关可点击电话号码的相关问题,另请参阅 my answer

【讨论】: