I would like to animate the alpha of an element fr...
# compose
m
I would like to animate the alpha of an element from 0f to 1f when a given screen becomes visible. In SwiftUI I implemented the visibility change with the
onAppear
modifier, however, looks like there isn’t a similar option with Compose. I looked over the
Animation
docs, but can’t seem to find a non-state based animation, which leads me to believe I need to have state that changes when the screen becomes visible?
r
If you want to manually drive the value of a non-state based animation, you can go one step lower and use the
Animatable
API.
m
It looks to me as if the higher level compose animation APIs are suitable, just wondering how to go about triggering a single shot animation when a view becomes visible
a
Check
AnimatedVisibility
.
m
Thanks, I looked into it but found it also requires state. What I would like is just a one shot animation that would be triggered on
onAppear
, but it looks like something like this does not exist and thus it’s necessary to have a state that gets updated when the view becomes visible. The only thing I could think of for this is mutating the state value in
LaunchedEffect
. So, could the answer be to do this:
Copy code
var visibleStateForAnimation by remember { mutableStateOf(false) }
    LaunchedEffect(null) {
        visibleStateForAnimation = true
    }
I’m not too familiar with
LaunchedEffect
so not quite sure about passing
null
as the key 🤔
It does work, but feels a bit hacky 🤷
Finally stumbled on the correct spot in the docs to verify the above: https://developer.android.com/jetpack/compose/side-effects#rememberupdatedstate Thanks for the help, looks as if this is the way to go 👍
d
AnimatedVisibility
combined with
MutableTransitionState
would allow you to start an animation going from not visible to visible:
Copy code
AnimatedVisibility(
                visibleState = remember {
                    // This sets up the initial state of the AnimatedVisibility to false to
                    // guarantee an initial enter transition. In contrast, initializing this as
                    // `MutableTransitionState(visible)` would result in no initial enter
                    // transition.
                    MutableTransitionState(initialState = false)
                }.apply {
                    // This changes the target state of the visible state. If it's different than
                    // the initial state, an enter/exit transition will be triggered.
                    targetState = true
                },
            ) { // Content that needs to appear/disappear goes here:
                ...
            }