如何在Jetpack Compose中设置按钮的宽度动画

时间:2020-06-14 18:25:25

标签: android android-jetpack-compose

假设我有一个这样的Composable:

@Composable
fun LoadingButton() {
    val (isLoading, setIsLoading) = state { false }

    Button(
        onClick = setIsLoading,
        text = {
            if (isLoading) {
                Text(text = "Short text")
            } else {
                Text(text = "Very very very long text")
            }
        }
    )
}

如何为按钮的宽度更新设置动画?

我很清楚,我可以在按钮上添加preferredWidth修饰符,并使用:来设置该宽度的动画:

val buttonWidth = animate(target = if (isLoading) LoadingButtonMinWidth else LoadingButtonMaxWidth)

但这不是我想要的。我需要设置自动“包裹内容”宽度的动画。

谢谢。

2 个答案:

答案 0 :(得分:2)

您需要将animateContentSize修饰符添加到Text Composable:

@Composable
fun LoadingButton() {
    val (isLoading, setIsLoading) = state { false }
    Button(onClick = { setIsLoading(!isLoading) }) {
        Text(
            text = if (isLoading) {
               "Short text"
            } else {
                "Very very very long text"
            },
            modifier = Modifier.animateContentSize()
        )
    }
}

答案 1 :(得分:2)

使用 1.0.0(使用 1.0.0-beta09 测试)您可以应用修饰符 animateContentSize

当它的子修改器(或者子可组合,如果它已经在链的尾部)改变大小时,这个修改器会为自己的大小设置动画。这允许父修饰符观察平滑的大小变化,从而导致整体连续的视觉变化。

类似于:

var isLoading by remember { mutableStateOf(false) }
val text = if (isLoading) "Short text" else "Very very very long text"

Button(onClick = { isLoading = !isLoading },
    modifier = Modifier
        .animateContentSize(
              animationSpec = tween(durationMillis = 300,
                   easing = LinearOutSlowInEasing))
) {
    Text(
        text = text,textAlign = TextAlign.Center
    )
}

enter image description here