28

I want to display a dynamic multiple lines text and an icon at the end of the last line. This icon can be animate. I try some ways but not success yet. How should I do?

Example view which had the same idea with my layout

enter image description here

3

1 Answer 1

52

In the Text composable you can use the inlineContent to define a map of tags that replaces certain ranges of the text. It's used to insert composables into text layout.
Then using a Placeholder you can reserve space in text layout.

Something like:

val myId = "inlineContent"
val text = buildAnnotatedString {
    append("Where do you like to go?")
    // Append a placeholder string "[icon]" and attach an annotation "inlineContent" on it.
    appendInlineContent(myId, "[icon]")
}

val inlineContent = mapOf(
    Pair(
        // This tells the [CoreText] to replace the placeholder string "[icon]" by
        // the composable given in the [InlineTextContent] object.
        myId,
        InlineTextContent(
            // Placeholder tells text layout the expected size and vertical alignment of
            // children composable.
            Placeholder(
                width = 12.sp,
                height = 12.sp,
                placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
            )
        ) {
            // This Icon will fill maximum size, which is specified by the [Placeholder]
            // above. Notice the width and height in [Placeholder] are specified in TextUnit,
            // and are converted into pixel by text layout.
            
            Icon(Icons.Filled.Face,"",tint = Color.Red)
        }
    )
)

Text(text = text,
     modifier = Modifier.width(100.dp),
     inlineContent = inlineContent)

enter image description here

It is a composable so you can use your favorite animation.

Just an example:

var blue by remember { mutableStateOf(false) }
val color by animateColorAsState(if (blue) Blue else Red,
    animationSpec = tween(
        durationMillis = 3000
    ))

and change the Icon to

Icon(Icons.Filled.Face,"", tint = color)

enter image description here

2
  • Notice that Placeholder contains useful parameters. There are icon's width and height as well as placeholderVerticalAlign which is very useful to align Icon in the text.
    – CoolMind
    Commented Apr 12 at 9:31
  • To convert dp to sp see stackoverflow.com/questions/65893939/…. Also you can add a space before Icon via modifier.
    – CoolMind
    Commented Apr 12 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.