如何在Jetpack Compose中实现TextStyle动画?

3
当某个布尔变量为真时,我 Composables 中的文本被划掉了。如何在重新组合时通过动画来改变 TextStyle,使得这条线条是淡入而不是突然出现和消失?
@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)
    )

你想要如何制作动画? - undefined
@GabrieleMariotti 感谢你指出这一点,我在我的问题中进行了澄清! - undefined
2个回答

5

不确定是否存在一种方法来使 TextStyle 动画化。
虽然不是最好的解决方案,但可以使用以下方法:

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


1
Gabriele的回答也是一个不错的解决方法,但或许更简单的方法是将Text和"Stroke"放在一个重叠的框中。比如说:
@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
   }
  }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接