Android 撰写文本的自动链接

Sir*_*lon 11 android textview android-jetpack-compose

有没有办法在 JetPack Compose Text 上使用android:autoLink功能?

我知道,在一个简单的标签/修饰符中使用此功能可能不是“声明性方式”,但也许有一些简单的方法?

对于文本样式我可以使用这种方式

 val apiString = AnnotatedString.Builder("API provided by")
        apiString.pushStyle(
            style = SpanStyle(
                color = Color.Companion.Blue,
                textDecoration = TextDecoration.Underline
            )
        )
        apiString.append("https://example.com")

        Text(text = apiString.toAnnotatedString())
Run Code Online (Sandbox Code Playgroud)

但是,我该如何管理这里的点击呢?如果我以编程方式说出我期望系统(电子邮件、电话、网络等)的行为,那就太好了。喜欢它。与 TextView 一起使用。谢谢

Mut*_*ran 4

我们可以在 Android Compose 中实现Linkify,如下TextView例所示,

@Composable
fun LinkifySample() {
    val uriHandler = UriHandlerAmbient.current

    val layoutResult = remember {
        mutableStateOf<TextLayoutResult?>(null)
    }

    val text = "API provided by"
    val annotatedString = annotatedString {
        pushStyle(
            style = SpanStyle(
                color = Color.Companion.Blue,
                textDecoration = TextDecoration.Underline
            )
        )
        append(text)
        addStringAnnotation(
            tag = "URL",
            annotation = "https://example.com",
            start = 0,
            end = text.length
        )
    }
    Text(
        fontSize = 16.sp,
        text = annotatedString, modifier = Modifier.tapGestureFilter { 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 }
    )
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我们可以看到我们给出了文本,并且还用于addStringAnnotation设置标签。使用 tapGestureFilter,我们可以获得点击的注释。

最后使用UriHandlerAmbient.current我们可以打开电子邮件、电话或网络等链接。

参考: https: //www.hellsoft.se/rendering-markdown-with-jetpack-compose/