您可以在單一字串中支援多個連結,以便在點選文字的子區段時執行不同動作。
結果
版本相容性
這項實作作業需要將專案 minSDK 設為 API 級別 21 以上。
依附元件
在單一字串中顯示多重連結
這個程式碼片段會將多個可點選的連結嵌入單一字串:
@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(".") } ) }
程式碼重點
- 使用
buildAnnotatedString函式建立帶註解的文字字串。 - 將連結和文字樣式做為
LinkAnnotation.Url()函式的引數 (本身會做為withLink()函式的引數),即可指定連結和文字樣式。點擊事件監聽器已內建於LinkAnnotation.Url()。 - 在
withLink函式主體中,使用append()新增文字。 - 重複這個程序,新增另一個連結的文字區段。
包含本指南的集合
本指南是精選快速指南系列的一部分,涵蓋更廣泛的 Android 開發目標:
顯示文字
文字是任何 UI 的核心元素。瞭解在應用程式中呈現文字的不同方式,提供令人愉悅的使用者體驗。
如有問題或想提供意見
前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。