Is there a better way to delay the `AnimatedVisibi...
# compose
v
Is there a better way to delay the
AnimatedVisibility
execution? Code in thread.
Copy code
var state by remember {
            mutableStateOf(false)
        }

LaunchedEffect(Unit) {
            delay(500)
            state = true
        }

AnimatedVisibility(
            visible = state,
            enter = slideInHorizontally(
                initialOffsetX = {
                    -it
                }
            )
        )
this one does work
Copy code
AnimatedVisibility(
            visible = true,
            enter = slideInHorizontally(
                initialOffsetX = {
                    -it
                },
                animationSpec = tween(durationMillis = 2000, delayMillis = 1000)
            )
        )
this one doesn't
c
AnimatedVisibility is animating state changes only. When you pass true as an initial parameter to it it is not animating anything. You need to pass false to visible first and then change the visibility to true in order to see an animation
but you can create your own animation that is started once when your Composable enters the composition
v
Got it, thanks a lot.
👍 1
d
You could also use a
MutableTransitionState
with AnimatedVisibility to create an animation that has a different target state than initial state:
Copy code
AnimatedVisibility(
            visibleState = remember { MutableTransitionState(false).apply { targetState = true } },
            enter = slideInHorizontally(
                initialOffsetX = {
                    -it
                },
                animationSpec = tween(durationMillis = 2000, delayMillis = 1000)
            )
        ) { ... }
🙏 1
v
So when we set
targetState
to another value, does it trigger the recomposition of animation? This is the same as
mutableStateOf()
, but for the animation particularly. Just trying to understand how it works.
c
Just look into the implementation of AnimatedVisibility. But in short, yes it does trigger the animation that you define, when the value of the visible parameter is changed. It “remembers” the current state, and if in the next recomposition you provide a different value it starts the “show” or “hide” animation
d
So when we set
targetState
to another value, does it trigger the recomposition of animation?
Yes.
targetState
in
MutableTransitionState
is backed by a mutable state: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]in/kotlin/androidx/compose/animation/core/Transition.kt;l=114 So when targetState changes, recomposition gets triggered and so do animations.
MutableTransitionState
allows you to define a different initial state than target state, which will run the animation immediately after the animation (e.g. Transition, AnimatedVisibility) that reads
MutableTransitionState
is composed for the first time.
1174 Views