Jetpack Compose 在 Text
中实现了细粒度的交互性。现在,文本选择更加灵活,可以在可组合布局中进行。文本中的用户互动与其他可组合布局不同,因为您无法将修饰符添加到 Text
可组合项的某个部分。本页面重点介绍了支持用户互动的 API。
选择文本
默认情况下,可组合项是不可选择的,这意味着用户无法从您的应用中选择和复制文本。要启用文本选择,请用 SelectionContainer
可组合项封装您的文本元素
@Composable fun SelectableText() { SelectionContainer { Text("This text is selectable") } }
您可能希望在可选择区域的特定部分禁用选择。为此,您需要使用 DisableSelection
可组合项封装不可选择的部分
@Composable fun PartiallySelectableText() { SelectionContainer { Column { Text("This text is selectable") Text("This one too") Text("This one as well") DisableSelection { Text("But not this one") Text("Neither this one") } Text("But again, you can select this one") Text("And this one too") } } }
使用 LinkAnnotation
创建文本的可点击部分
要侦听 Text
上的点击事件,您可以添加 clickable
修饰符。但是,您可能希望将额外的信息附加到 Text
值的某个部分,例如附加到某个单词的 URL,以便在浏览器中打开。在这种情况下,您需要使用 LinkAnnotation
,它是一个表示文本可点击部分的注解。
使用 LinkAnnotation
,您可以将 URL 附加到 Text
可组合项的某个部分,该 URL 在点击后会自动打开,如以下代码段所示
@Composable fun AnnotatedStringWithLinkSample() { // Display multiple links in the text Text( buildAnnotatedString { append("Go to the ") withLink( LinkAnnotation.Url( "https://developer.android.com/", TextLinkStyles(style = SpanStyle(color = Color.Blue)) ) ) { append("Android Developers ") } append("website, and check out the") withLink( LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(style = SpanStyle(color = Color.Green)) ) ) { append("Compose guidance") } append(".") } ) }
您还可以配置自定义操作,以响应用户点击 Text
可组合项的某个部分。在以下代码段中,当用户点击“Jetpack Compose”时,会显示一个链接,如果用户点击该链接,则会记录指标
@Composable fun AnnotatedStringWithListenerSample() { // Display a link in the text and log metrics whenever user clicks on it. In that case we handle // the link using openUri method of the LocalUriHandler val uriHandler = LocalUriHandler.current Text( buildAnnotatedString { append("Build better apps faster with ") val link = LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(SpanStyle(color = Color.Blue)) ) { val url = (it as LinkAnnotation.Url).url // log some metrics uriHandler.openUri(url) } withLink(link) { append("Jetpack Compose") } } ) }
为您推荐
- 注意:当 JavaScript 关闭时,会显示链接文本
- Compose 中的语义
- Compose 中的无障碍功能
- Compose 中的 Material Design 2