Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate TextStyle in Jetpack Compose?

The text in one of my Composables is struck-through when a certain boolean variable is true. How can I animate this change in TextStyle on recomposition so that the line fades in rather than appearing and disappearing abruptly?

@Composable
fun MyComposable(
    completed: Boolean
) {
    val textStyle = TextStyle(textDecoration = if (completed) TextDecoration.LineThrough else null)

    Text(
        text = title,
        color = textColor,
        style = textStyle,
        modifier = Modifier.align(Alignment.CenterVertically)
    )
like image 842
Florian Walther Avatar asked Sep 12 '25 17:09

Florian Walther


2 Answers

Not sure if it exists a way to animate a TextStyle.
Not a great solution, but just a workaround:

Box() {
    AnimatedVisibility(
        visible = !completed,
        enter = fadeIn(
            animationSpec = tween(durationMillis = duration)
        ),
        exit = fadeOut(
            animationSpec = tween(durationMillis = duration)
        )) {
        Text(
            text = title,
            style = TextStyle(textDecoration=null)
        )
    }
    AnimatedVisibility(
        visible = completed,
        enter = fadeIn(
            animationSpec = tween(durationMillis = duration)
        ),
        exit = fadeOut(
            animationSpec = tween(durationMillis = duration)
        )) {
        Text(
            text = title,
            style = TextStyle(textDecoration = TextDecoration.LineThrough),
        )
    }
}

enter image description here

like image 190
Gabriele Mariotti Avatar answered Sep 14 '25 07:09

Gabriele Mariotti


Gabriele's answer is also a decent workaround, but perhaps a simpler one would be to put the Text and the "Stroke", in a box, overlapping. Say,

@Composable
fun MyComposable(
    completed: Boolean
) {

Box{
    Text(
        text = title,
        color = textColor,
        style = textStyle,
        modifier = Modifier.align(Alignment.CenterVertically)
    )
  AnimatedVisibility (completed) {
   Box(Modifier.width(1.dp)){
     //Empty Box of unit width to serve as the stroke
    // Add background modifiers to match the font color
   }
  }
}

like image 38
MARSK Avatar answered Sep 14 '25 07:09

MARSK