gpt4 book ai didi

android - 使用撰写文本链接

转载 作者:行者123 更新时间:2023-12-04 23:40:17 28 4
gpt4 key购买 nike

我找不到如何链接我的 Text()使用 Jetpack Compose。
在作曲之前,我所要做的就是:Linkify.addLinks(myTextView, Linkify.EMAIL_ADDRESSES or Linkify.WEB_URLS)显然,我的 TextView 中包含的所有链接都变成了可点击的链接。
重要提示:文本的内容来自 API,链接没有固定位置,内容可能包含多个链接。
我想通过使用 Jetpack Compose 来保持这种行为,但我找不到任何关于这样做的信息。
有人知道吗?

最佳答案

如果有人正在寻找解决方案,以下内容将使您的文本中的任何链接都可点击和样式化:

@Composable
fun LinkifyText(text: String, modifier: Modifier = Modifier) {
val uriHandler = LocalUriHandler.current
val layoutResult = remember {
mutableStateOf<TextLayoutResult?>(null)
}
val linksList = extractUrls(text)
val annotatedString = buildAnnotatedString {
append(text)
linksList.forEach {
addStyle(
style = SpanStyle(
color = Color.Companion.Blue,
textDecoration = TextDecoration.Underline
),
start = it.start,
end = it.end
)
addStringAnnotation(
tag = "URL",
annotation = it.url,
start = it.start,
end = it.end
)
}
}
Text(text = annotatedString, style = MaterialTheme.typography.body1, modifier = modifier.pointerInput(Unit) {
detectTapGestures { offsetPosition ->
layoutResult.value?.let {
val position = it.getOffsetForPosition(offsetPosition)
annotatedString.getStringAnnotations(position, position).firstOrNull()
?.let { result ->
if (result.tag == "URL") {
uriHandler.openUri(result.item)
}
}
}
}
},
onTextLayout = { layoutResult.value = it }
)
}

private val urlPattern: Pattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE or Pattern.MULTILINE or Pattern.DOTALL
)

fun extractUrls(text: String): List<LinkInfos> {
val matcher = urlPattern.matcher(text)
var matchStart: Int
var matchEnd: Int
val links = arrayListOf<LinkInfos>()

while (matcher.find()) {
matchStart = matcher.start(1)
matchEnd = matcher.end()

var url = text.substring(matchStart, matchEnd)
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "https://$url"

links.add(LinkInfos(url, matchStart, matchEnd))
}
return links
}

data class LinkInfos(
val url: String,
val start: Int,
val end: Int
)

关于android - 使用撰写文本链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66130513/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com