Crossfade

Composable Function

Common
@Composable
public fun <T> Crossfade(
    targetState: T,
    modifier: Modifier = Modifier,
    animationSpec: FiniteAnimationSpec<Float> = tween(),
    label: String = "Crossfade",
    content: @Composable (T) -> Unit,
)

Crossfade allows to switch between two layouts with a crossfade animation.

Parameters

targetStateis a key representing your target layout state. Every time you change a key the animation will be triggered. The content called with the old key will be faded out while the content called with the new key will be faded in.
modifierModifier to be applied to the animation container.
animationSpecthe AnimationSpec to configure the animation.
labelAn optional label to differentiate from other animations in Android Studio.
contentA mapping from a given state to the content corresponding to that state.
Common

Deprecated Crossfade API now has a new label parameter added.

@Composable
public fun <T> Crossfade(
    targetState: T,
    modifier: Modifier = Modifier,
    animationSpec: FiniteAnimationSpec<Float> = tween(),
    content: @Composable (T) -> Unit,
)
Common
@ExperimentalAnimationApi
@Composable
public fun <T> Transition<T>.Crossfade(
    modifier: Modifier = Modifier,
    animationSpec: FiniteAnimationSpec<Float> = tween(),
    contentKey: (targetState: T) -> Any? = { it },
    content: @Composable (targetState: T) -> Unit,
)

Crossfade allows to switch between two layouts with a crossfade animation. The target state of this Crossfade will be the target state of the given Transition object. In other words, when the Transition changes target, the Crossfade will fade in the target content while fading out the current content.

content is a mapping between the state and the composable function for the content of that state. During the crossfade, content lambda will be invoked multiple times with different state parameter such that content associated with different states will be fading in/out at the same time.

contentKey will be used to perform equality check for different states. For example, when two states resolve to the same content key, there will be no animation for that state change. By default, contentKey is the same as the state object. contentKey can be particularly useful if target state object gets recreated across save & restore while a more persistent key is needed to properly restore the internal states of the content.

Parameters

modifierModifier to be applied to the animation container.
animationSpecthe AnimationSpec to configure the animation.
contentKeyA mapping from a given state to an object of Any.
contentA mapping from a given state to the content corresponding to that state.

Code Examples

CrossfadeSample

@Composable
fun CrossfadeSample() {
    Crossfade(targetState = "A") { screen ->
        when (screen) {
            "A" -> Text("Page A")
            "B" -> Text("Page B")
        }
    }
}