I am familiar with the Transition
API in Jetpack Compose that lets me easily animate between two states inside a Compose component.
But what would be the best way to animate between three different states?
Consider as an example a loading indicator for a component. The states could be NotLoading, Loading and HasLoaded. My thinking here would be to have a loading indicator for a component and transition between those states:
- Transition for showing the loading indicator: NotLoading -> Loading
- Transition for showing the data: Loading -> HasLoaded
I guess what kind of transition doesn't really matter but I was thinking first fade in loading indicator then fade out loading indicator and fade in content. But this is just an example; in reality I need to specify the transition parameters.
What would be the best way to achieve this with Jetpack Compose? Not sure if my state thinking here is the best approach for this either.
You can use the
Transition
API with more than 2 states - and define the individual properties of each component usinganimate*AsState
APIs.There is another option if you have completely different Composables, you can use the
AnimatedContent
APIs.For example, the below sample uses an enum
UiState
, and a button to change between the states. The content is then wrapped inside theAnimatedContent()
composable. By default, the initial content fades out and then the target content fades in (this behavior is called fade through).You can customize this animation behavior by specifying a
ContentTransform
object to thetransitionSpec
parameter. You can createContentTransform
by combining anEnterTransition
with anExitTransition
using the with infix function. You can applySizeTransform
to theContentTransform
by attaching it with the using infix function.More information about
AnimatedContent
can be found here: https://developer.android.com/jetpack/compose/animation#animatedcontent.And samples of its usage here: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/animation/animation/samples/src/main/java/androidx/compose/animation/samples/AnimatedContentSamples.kt