Jetpack Compose 可在 Text
中啟用精細的互動功能。文字選取為
現在變得更有彈性,並且可以在可組合函式中完成。使用者互動
文字與可組合函式的版面配置不同,因為您無法新增修飾符
加到 Text
可組合項的一部分本頁面將重點介紹
讓使用者進行互動
選取文字
根據預設,可組合函式無法選取,這表示使用者無法
選取並複製應用程式中的文字如要啟用文字選取功能,請換行
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
值,例如附加至特定字詞,以開啟
。在此情況下,您必須使用 LinkAnnotation
,也就是
代表文字中可點擊部分的註解。
您可以使用 LinkAnnotation
,將網址附加至 Text
可組合項的一部分
點擊會自動開啟,如以下程式碼片段所示:
@Composable fun AnnotatedStringWithLinkSample() { // Display a link in the text Text( buildAnnotatedString { append("Build better apps faster with ") withLink( LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(style = SpanStyle(color = Color.Blue)) ) ) { append("Jetpack Compose") } } ) }
您也可以設定自訂動作,回應使用者
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 中的質感設計 2