Show inline content with Ellipsis overflow in Jetpack Compose Text doesn't work

202 views Asked by At

Tried to implement Text with timestamp. Found that easiest way it's use inlineContent. But it doesn't work well with overflow = TextOverflow.Ellipsis

@Composable
fun TextWithTimestamp(
    text: String,
    timestamp: String,
    maxLines: Int,
    modifier: Modifier = Modifier,
) {

    val annotatedString = buildAnnotatedString {
        withStyle(style = SpanStyle(color = Color.White)) {
            append(text)
        }
        pushStyle(SpanStyle(fontSize = 14.sp))
        appendInlineContent("timestamp", timestamp)
        pop()
    }

    val inlineContent = remember(text) {
        mutableMapOf(
            "timestamp" to InlineTextContent(
                placeholder = Placeholder(
                    height = 20.sp,
                    width = 20.sp,
                    placeholderVerticalAlign = PlaceholderVerticalAlign.Center,
                ),
                children = {
                    Text(
                        text = it,
                        color = Color.Yellow,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            )
        )
    }

    Text(
        text = annotatedString,
        inlineContent = inlineContent,
        maxLines = maxLines,
        overflow = TextOverflow.Ellipsis,
    )
}

@Preview(widthDp = 200)
@Composable
private fun PreviewTextWithTimestamp() {
    Column(
        modifier = Modifier
            .padding(16.dp)
            .border(1.dp, Color.Green)
    ) {
        TextWithTimestamp(
            text = "MedalParrot, MedalPanda, MedalCarrot and 83+ liked your clip!",
            timestamp = "1h",
            maxLines = 2,
        )
        Divider(color = Color.Green)
        TextWithTimestamp(
            text = "MedalParrot, MedalPanda, MedalCarrot and 83+ liked your clip!",
            timestamp = "1h",
            maxLines = 3,
        )
    }
}

Without overflow, it works as expected, but with TextOverflow.Ellipsis, only ... is shown, but inline content doesn't.

In design, I have limitation of content width and defined max lines. The text can be any length:

Preview with maxLines = 2 and maxLines = 3

0

There are 0 answers