Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Created December 18, 2023 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeyls/cf6beec555f053cf2a74654829fda682 to your computer and use it in GitHub Desktop.
Save cbeyls/cf6beec555f053cf2a74654829fda682 to your computer and use it in GitHub Desktop.
Material 2 ClickableText
@Composable
fun MaterialClickableText(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current,
onClick: (Int) -> Unit
) {
val localContentColor = LocalContentColor.current
val localContentAlpha = LocalContentAlpha.current
val overrideColorOrUnspecified: Color = if (color.isSpecified) {
color
} else if (style.color.isSpecified) {
style.color
} else {
localContentColor.copy(localContentAlpha)
}
val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val pressIndicator = Modifier.pointerInput(onClick) {
detectTapGestures { pos ->
layoutResult.value?.let { layoutResult ->
onClick(layoutResult.getOffsetForPosition(pos))
}
}
}
BasicText(
text = text,
modifier = modifier.then(pressIndicator),
style = style.merge(
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing
),
onTextLayout = {
layoutResult.value = it
onTextLayout(it)
},
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
minLines = minLines,
inlineContent = inlineContent,
color = { overrideColorOrUnspecified }
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment