啟用使用者互動

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")
        }
    }
}

較長的文字段落。使用者嘗試選取整個段落,但由於兩行套用了 EnableSelection,因此並未選取。

取得點選文字的位置

如要監聽 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)
        }
    })
}