Jetpack Compose:在Composable Text中检测链接并实现可点击高亮
在Jetpack Compose中实现可点击高亮的URL文本展示
给定如下文本:
Android is a mobile operating system https://www.android.com/ based on a modified version of the Linux kernel http://hellosite.com/4dnfsddp and other open-source software.
我们需要在Jetpack Compose的ClickableText组件中实现自动检测URL、高亮显示并支持点击跳转的效果(URL显示为蓝色下划线样式,点击可打开对应链接)。
实现步骤与代码示例:
- 编写URL匹配正则:用于从文本中提取所有URL
- 构建带注解的字符串(AnnotatedString):给匹配到的URL添加高亮样式和点击标记
- 使用ClickableText渲染:处理点击事件,打开对应URL
完整代码如下:
import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.foundation.text.ClickableText import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import java.util.regex.Pattern // 匹配URL的正则表达式 private val URL_PATTERN = Pattern.compile( "((https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])" ) @Composable fun UrlClickableText(text: String) { val context = LocalContext.current val annotatedString = buildAnnotatedString { append(text) val matcher = URL_PATTERN.matcher(text) while (matcher.find()) { val url = matcher.group() url?.let { // 添加点击标记 addStringAnnotation( tag = "URL", annotation = it, start = matcher.start(), end = matcher.end() ) // 设置高亮样式:蓝色+下划线 addStyle( style = SpanStyle( color = Color(0xFF1A73E8), textDecoration = TextDecoration.Underline ), start = matcher.start(), end = matcher.end() ) } } } ClickableText( text = annotatedString, style = MaterialTheme.typography.body1 ) { offset -> // 处理点击事件 annotatedString.getStringAnnotations("URL", offset, offset) .firstOrNull()?.let { annotation -> openUrl(context, annotation.item) } } } // 打开URL的工具方法 private fun openUrl(context: Context, url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) context.startActivity(intent) } @Preview @Composable fun PreviewUrlClickableText() { val sampleText = "Android is a mobile operating system https://www.android.com/ based on a modified version of the Linux kernel http://hellosite.com/4dnfsddp and other open-source software." UrlClickableText(text = sampleText) }
效果说明:
运行上述代码后,文本中的URL会自动被识别,显示为蓝色带下划线的样式;点击URL时,会调用系统浏览器打开对应的链接,完全符合需求中的展示效果。
内容的提问来源于stack exchange,提问作者AndroidDev
相关产品推荐
相关产品推荐

