我认为淡出动画实际上是“本身”正常工作的。
我怀疑参数text:String?
是来自上面某个地方提升的“状态”的值,因为您直接观察它位于动画范围内,当您将其更改为null时,它会立即删除Text
组合,并且您不会见证缓慢的淡出。
AnimatedVisibility(
...
) {
text?.let {
Text(text = it)
}
}
我根据自己的理解对你的片段进行了尝试并使其能够正常工作,淡入效果可以实现,但所需的淡出效果立即发生。
@Composable
fun SomeScreen() {
var text by remember {
mutableStateOf<String?>("Initial Value")
}
Row(
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = {
text = "New Value"
}) {
Text("Set New Value")
}
Button(onClick = {
text = null
}) {
Text("Remove Value")
}
AnimatedText(text = text)
}
}
@Composable
fun ShowAnimatedText(
text : String?
) {
Column(
modifier = Modifier.fillMaxWidth()
) {
AnimatedVisibility(
visible = text != null,
enter = fadeIn(animationSpec = tween(2000)),
exit = fadeOut(animationSpec = tween(2000))
) {
text?.let {
Text(text = it)
}
}
}
}
您可以通过将text
修改为非状态值,并将可见性逻辑从使用可空性检查更改为某些需要它为visible
或hidden
的“业务逻辑”来解决此问题,如下所示修改上面的代码。
@Composable
fun SomeScreen() {
var show by remember {
mutableStateOf(true)
}
Row(
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = {
show = !show
}) {
Text("Set New Value")
}
AnimatedText(text = "Just A Value", show)
}
}
@Composable
fun ShowAnimatedText(
text : String?,
show: Boolean
) {
Column(
modifier = Modifier.fillMaxWidth()
) {
AnimatedVisibility(
visible = show,
enter = fadeIn(animationSpec = tween(2000)),
exit = fadeOut(animationSpec = tween(2000))
) {
text?.let {
Text(text = it)
}
}
}
}
![enter image description here](https://istack.dev59.com/xh8q5.gif)