启用用户互动

Jetpack Compose 在 Text 中实现了细粒度的交互性。现在,文本选择更加灵活,可以在可组合布局中进行。文本中的用户互动与其他可组合布局不同,因为您无法将修饰符添加到 Text 可组合项的某个部分。本页面重点介绍了支持用户互动的 API。

选择文本

默认情况下,可组合项是不可选择的,这意味着用户无法从您的应用中选择和复制文本。要启用文本选择,请用 SelectionContainer 可组合项封装您的文本元素

@Composable
fun SelectableText() {
    SelectionContainer {
        Text("This text is selectable")
    }
}

A short passage of text, selected by the user.

您可能希望在可选择区域的特定部分禁用选择。为此,您需要使用 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")
        }
    }
}

A longer passage of text. The user tried to select the whole passage, but since two lines had DisableSelection applied, they were not selected.

使用 LinkAnnotation 创建文本的可点击部分

要侦听 Text 上的点击事件,您可以添加 clickable 修饰符。但是,您可能希望将额外的信息附加到 Text 值的某个部分,例如附加到某个单词的 URL,以便在浏览器中打开。在这种情况下,您需要使用 LinkAnnotation,它是一个表示文本可点击部分的注解。

使用 LinkAnnotation,您可以将 URL 附加到 Text 可组合项的某个部分,该 URL 在点击后会自动打开,如以下代码段所示

您还可以配置自定义操作,以响应用户点击 Text 可组合项的某个部分。在以下代码段中,当用户点击“Jetpack Compose”时,会显示一个链接,如果用户点击该链接,则会记录指标