如何将AnimatedVisibility与可为null的值一起使用



我经常遇到这种情况。我在下面的示例中有一些值,比如plates,我想根据它是否为null来显示/隐藏它。但是隐藏它总是失败的,因为无论何时它为空,都不会渲染任何东西,并且动画只是捕捉到空的虚无。

我该如何完成此操作?我想让plates一直存在,直到动画结束

AnimatedVisibility(
visible = plates != null,
content = {
if (plates != null) {
// Render plates
} else {
// The animation snaps to nothingness, as opposed to animating out
}
})

这就是我最终所做的,并且它按预期工作!

@Composable
inline fun <T> AnimatedValueVisibility(
value: T?,
enter: EnterTransition = fadeIn(
animationSpec = FloatSpec
) + expandVertically(
animationSpec = SizeSpec,
clip = false
),
exit: ExitTransition = fadeOut(
animationSpec = FloatSpec
) + shrinkVertically(
animationSpec = SizeSpec,
clip = false
),
crossinline content: @Composable (T) -> Unit
) {
val ref = remember {
Ref<T>()
}
ref.value = value ?: ref.value
AnimatedVisibility(
visible = value != null,
enter = enter,
exit = exit,
content = {
ref.value?.let { value ->
content(value)
}
}
)
}

我可能会迟到一点,但也有AnimatedContent可组合。它仍然需要选择加入ExperimentalAnimationApi,但是它会通过其可组合的lambda参数将模型向下传递,并且您可以检查该参数是否为null。以下是它的工作方式:

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.runtime.Composable
@Composable
@OptIn(ExperimentalAnimationApi::class)
fun AnimatedPlates(plates: Plates?) {
AnimatedContent(plates) { plates ->
if (plates != null) {
// Render plates
} else {
// Render either nothing, or some empty state.
}
}
}

我希望这能有所帮助!

动画总是需要内容,即使没有任何内容可以显示。当内容为空(或空(时只显示一个表面:

AnimatedVisibility(
visible = plates != null,
content = {
if (plates != null) {
// Render plates
} else {
Surface(modifier = Modifier.fillMaxSize()) { }
}
})

相关内容

最新更新