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") } } }
取得點選文字的位置
如要監聽 Text
上的點擊,您可以新增 clickable
修飾符。但是,如果您想在 Text
可組合項中取得點擊的位置,在對文字的不同部分執行不同動作的情況下,就必須改用 ClickableText
:
@Composable fun SimpleClickableText() { ClickableText(text = AnnotatedString("Click Me"), onClick = { offset -> Log.d("ClickableText", "$offset -th character is clicked.") }) }
附帶備註的點擊
當使用者按一下 Text
可組合項時,您可能需要在部分 Text
值中附加額外資訊,例如附加至特定字詞,以便在瀏覽器中開啟的網址。如要執行此操作,您必須附加註解,以標記 (String
)、項目 (String
) 和文字範圍做為參數。使用 AnnotatedString
即可依標記或文字範圍篩選這些註解。範例如下:
@Composable fun AnnotatedClickableText() { val annotatedText = buildAnnotatedString { append("Click ") // We attach this *URL* annotation to the following content // until `pop()` is called pushStringAnnotation( tag = "URL", annotation = "https://developer.android.com" ) withStyle( style = SpanStyle( color = Color.Blue, fontWeight = FontWeight.Bold ) ) { append("here") } pop() } ClickableText(text = annotatedText, onClick = { offset -> // We check if there is an *URL* annotation attached to the text // at the clicked position annotatedText.getStringAnnotations( tag = "URL", start = offset, end = offset ).firstOrNull()?.let { annotation -> // If yes, we log its value Log.d("Clicked URL", annotation.item) } }) }
為您推薦
- 注意:系統會在 JavaScript 關閉時顯示連結文字
- Compose 中的語意
- Compose 中的無障礙功能
- Compose 中的質感設計 2