假设我有一个这样的可组合对象:
@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)
但这不是我想要的。我需要为自动“wrap-content”宽度设置动画。
提前致谢。
您需要向
animateContentSize
可组合项添加一个 Text
修饰符:
@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()
)
}
}
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
)
}