Composable Function

ClickableText

A continent version of BasicText component to be able to handle click event on the text.

ClickableText

@Sampled
@Composable
@Suppress("Deprecation")
fun ClickableText() {
    ClickableText(
        text = AnnotatedString("Click Me"),
        onClick = { offset -> Log.d("ClickableText", "$offset -th character is clicked.") },
    )
}

LongClickableText

@Sampled
@Composable
fun LongClickableText(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    softWrap: Boolean = false,
    overflow: TextOverflow = TextOverflow.Clip,
    maxLines: Int = Int.MAX_VALUE,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    onLongClick: (offset: Int) -> Unit,
) {
    val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
    val gesture =
        Modifier.pointerInput(onLongClick) {
            detectTapGestures(
                onLongPress = { pos ->
                    layoutResult.value?.let { layout ->
                        onLongClick(layout.getOffsetForPosition(pos))
                    }
                }
            )
        }

    Text(
        text = text,
        modifier = modifier.then(gesture),
        style = style,
        softWrap = softWrap,
        overflow = overflow,
        maxLines = maxLines,
        onTextLayout = {
            onTextLayout(it)
            layoutResult.value = it
        },
    )
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: