【问题标题】:How to animate TextStyle in Jetpack Compose?如何在 Jetpack Compose 中为 TextStyle 设置动画?
【发布时间】:2021-07-29 23:56:11
【问题描述】:

当某个布尔变量为真时,我的一个 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)
    )

【问题讨论】:

  • 你想怎么做动画?
  • @GabrieleMariotti 谢谢你指出这一点,我在我的问题中澄清了!

标签: android android-jetpack-compose android-jetpack-compose-text


【解决方案1】:

不确定是否存在为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),
        )
    }
}

【讨论】:

    【解决方案2】:

    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
       }
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多