androidandroid-jetpack-composejetpack-compose-animationandroid-jetpack-compose-animation

How to animate item visibility only once with Jetpack Compose and AnimatedVisibility?


So when I add

val state = remember {
    MutableTransitionState(false)
}
state.targetState = true
AnimatedVisibility(
    visibleState = state,
    enter = slideInHorizontally(
        animationSpec = tween(
            durationMillis = 250,
            delayMillis = animationDelay
        ),
        initialOffsetX = {
            screenWidthPx
        }
    )
) {
    content()
}

the animation is being triggered all the time when I return to this screen from another (popBackStack/naivateUp) or during config changes.

How to animate it only once?


Solution

  • You are setting target state to true explicitly every time outside remember scope, now the target state would also be remembered and it wont animate unless you set target state to false

    val state = remember {
        MutableTransitionState(false).apply {
          targetState = true
        }
    }
    AnimatedVisibility(
        visibleState = state,
        enter = slideInHorizontally(
            animationSpec = tween(
                durationMillis = 250,
                delayMillis = animationDelay
            ),
            initialOffsetX = {
                screenWidthPx
            }
        )
    ) {
        content()
    }