SharedTransitionScope


SharedTransitionScope provides a coordinator space in which shared elements/ shared bounds (when matched) will transform their bounds from one to another. Their position animation is always relative to the origin defined by where SharedTransitionScope is in the tree.

SharedTransitionScope also creates an overlay, in which all shared elements and shared bounds are rendered by default, so that they are not subject to their parent's fading or clipping, and can therefore transform the bounds without alpha jumps or being unintentionally clipped.

It is also SharedTransitionScope's responsibility to do the SharedContentState key match for all the sharedElement or sharedBounds defined in this scope. Note: key match will not work for SharedContentState created in different SharedTransitionScopes.

SharedTransitionScope oversees all the animations in its scope. When any of the animations is active, isTransitionActive will be true. Once a bounds transform starts, by default the shared element or shared bounds will render the content in the overlay. The rendering will remain in the overlay until all other animations in the SharedTransitionScope are finished (i.e. when isTransitionActive == false).

Summary

Nested types

OverlayClip defines a specific clipping that should be applied to a sharedBounds or sharedElement in the overlay.

PlaceHolderSize defines the size of the space that was or will be occupied by the exiting or entering sharedElement/sharedBounds.

There are two different modes to resize child layout of sharedBounds during bounds transform: 1) ScaleToBounds and 2) RemeasureToBounds.

SharedContentState is designed to allow access of the properties of sharedBounds/sharedElement, such as whether a match of the same key has been found in the SharedTransitionScope, its clipPathInOverlay and parentSharedContentState if there is a parent sharedBounds in the layout tree.

Public functions

SharedTransitionScope.OverlayClip
OverlayClip(clipShape: Shape)

Creates an OverlayClip based on a specific clipShape.

Cmn
SharedTransitionScope.SharedContentState

Creates and remembers a SharedContentState with a given key.

Cmn
Modifier
Modifier.renderInSharedTransitionScopeOverlay(
    renderInOverlay: () -> Boolean,
    zIndexInOverlay: Float,
    clipInOverlayDuringTransition: (LayoutDirection, Density) -> Path?
)

Renders the content in the SharedTransitionScope's overlay, where shared content (i.e. shared elements and shared bounds) is rendered by default.

Cmn
open EnterTransition
scaleInSharedContentToBounds(
    contentScale: ContentScale,
    alignment: Alignment
)

This function is deprecated. This EnterTransition has been deprecated.

Cmn
open ExitTransition
scaleOutSharedContentToBounds(
    contentScale: ContentScale,
    alignment: Alignment
)

This function is deprecated. This ExitTransition has been deprecated.

Cmn
Modifier
Modifier.sharedBounds(
    sharedContentState: SharedTransitionScope.SharedContentState,
    animatedVisibilityScope: AnimatedVisibilityScope,
    enter: EnterTransition,
    exit: ExitTransition,
    boundsTransform: BoundsTransform,
    resizeMode: SharedTransitionScope.ResizeMode,
    placeHolderSize: SharedTransitionScope.PlaceHolderSize,
    renderInOverlayDuringTransition: Boolean,
    zIndexInOverlay: Float,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip
)

sharedBounds is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared bounds of the same key share the animated and continuously changing bounds during the layout change.

Cmn
Modifier
Modifier.sharedElement(
    sharedContentState: SharedTransitionScope.SharedContentState,
    animatedVisibilityScope: AnimatedVisibilityScope,
    boundsTransform: BoundsTransform,
    placeHolderSize: SharedTransitionScope.PlaceHolderSize,
    renderInOverlayDuringTransition: Boolean,
    zIndexInOverlay: Float,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip
)

sharedElement is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared elements of the same key share the animated and continuously changing bounds during the layout change.

Cmn
Modifier
Modifier.sharedElementWithCallerManagedVisibility(
    sharedContentState: SharedTransitionScope.SharedContentState,
    visible: Boolean,
    boundsTransform: BoundsTransform,
    placeHolderSize: SharedTransitionScope.PlaceHolderSize,
    renderInOverlayDuringTransition: Boolean,
    zIndexInOverlay: Float,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip
)

sharedElementWithCallerManagedVisibility is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared elements of the same key share the animated and continuously changing bounds during the layout change.

Cmn
Modifier

skipToLookaheadSize enables a layout to measure its child with the lookahead constraints, therefore laying out the child as if the transition has finished.

Cmn

Public properties

Boolean

Indicates whether there is any ongoing transition between matched sharedElement or sharedBounds.

Cmn

Inherited functions

From androidx.compose.ui.layout.LookaheadScope
open Offset
LayoutCoordinates.localLookaheadPositionOf(
    sourceCoordinates: LayoutCoordinates,
    relativeToSource: Offset,
    includeMotionFrameOfReference: Boolean
)

Converts relativeToSource in sourceCoordinates's lookahead coordinate space into local lookahead coordinates.

Cmn
LayoutCoordinates

Converts a LayoutCoordinates into a LayoutCoordinates in the Lookahead coordinate space.

Cmn

Public functions

OverlayClip

fun OverlayClip(clipShape: Shape): SharedTransitionScope.OverlayClip

Creates an OverlayClip based on a specific clipShape.

rememberSharedContentState

@Composable
fun rememberSharedContentState(key: Any): SharedTransitionScope.SharedContentState

Creates and remembers a SharedContentState with a given key.

renderInSharedTransitionScopeOverlay

fun Modifier.renderInSharedTransitionScopeOverlay(
    renderInOverlay: () -> Boolean = { isTransitionActive },
    zIndexInOverlay: Float = 0.0f,
    clipInOverlayDuringTransition: (LayoutDirection, Density) -> Path? = DefaultClipInOverlayDuringTransition
): Modifier

Renders the content in the SharedTransitionScope's overlay, where shared content (i.e. shared elements and shared bounds) is rendered by default. This is useful for rendering content that is not shared on top of shared content to preserve a specific spatial relationship.

renderInOverlay dynamically controls whether the content should be rendered in the SharedTransitionScope's overlay. By default, it returns the same value as SharedTransitionScope.isTransitionActive. This means the default behavior is to render the child layout of this modifier in the overlay only when the transition is active.

IMPORTANT: When elevating layouts into the overlay, the layout is no longer subjected to 1) its parent's clipping, and 2) parent's layer transform (e.g. alpha, scale, etc). Therefore, it is recommended to create an enter/exit animation (e.g. using AnimatedVisibilityScope.animateEnterExit) for the child layout to avoid any abrupt visual changes.

clipInOverlayDuringTransition supports a custom clip path if clipping is desired. By default, no clipping is applied. Manual management of clipping can often be avoided by putting layouts with clipping as children of this modifier (i.e. to the right side of this modifier).

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.Create
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// Create an Image that will be shared between the two shared elements.
@Composable
fun Cat(modifier: Modifier = Modifier) {
    Image(
        painterResource(id = R.drawable.yt_profile),
        contentDescription = "cute cat",
        contentScale = ContentScale.FillHeight,
        modifier = modifier.clip(shape = RoundedCornerShape(10))
    )
}

var showThumbnail by remember { mutableStateOf(true) }
SharedTransitionLayout(
    Modifier.clickable { showThumbnail = !showThumbnail }.fillMaxSize().padding(10.dp)
) {
    Column(Modifier.padding(10.dp)) {
        // Create an AnimatedVisibility for the shared element, so that the layout siblings
        // (i.e. the two boxes below) will move in to fill the space during the exit transition.
        AnimatedVisibility(visible = showThumbnail) {
            Cat(
                Modifier.size(100.dp)
                    // Create a shared element, using string as the key
                    .sharedElement(
                        rememberSharedContentState(key = "YT"),
                        this@AnimatedVisibility,
                    )
            )
        }
        Box(
            Modifier.fillMaxWidth()
                .height(100.dp)
                .background(Color(0xffffcc5c), RoundedCornerShape(5.dp))
        )
        Box(
            Modifier.fillMaxWidth()
                .height(100.dp)
                .background(Color(0xff2a9d84), RoundedCornerShape(5.dp))
        )
    }
    Box(modifier = Modifier.fillMaxSize()) {
        AnimatedVisibility(!showThumbnail) {
            Cat(
                Modifier.fillMaxSize()
                    // Create another shared element, and make sure the string key matches
                    // the other shared element.
                    .sharedElement(
                        rememberSharedContentState(key = "YT"),
                        this@AnimatedVisibility,
                    )
            )
        }
        FloatingActionButton(
            modifier =
                Modifier.padding(20.dp)
                    .align(Alignment.BottomEnd)
                    // During shared element transition, shared elements will be rendered in
                    // overlay to escape any clipping or layer transform from parents. It also
                    // means they will render over on top of UI elements such as Floating Action
                    // Button. Once the transition is finished, they will be dropped from the
                    // overlay to their own DrawScopes. To help support keeping specific UI
                    // elements always on top, Modifier.renderInSharedTransitionScopeOverlay
                    // will temporarily elevate them into the overlay as well. By default,
                    // this modifier keeps content in overlay during the time when the
                    // shared transition is active (i.e.
                    // SharedTransitionScope#isTransitionActive).
                    // The duration can be customize via `renderInOverlay` parameter.
                    .renderInSharedTransitionScopeOverlay(
                        // zIndexInOverlay by default is 0f for this modifier and for shared
                        // elements. By overwriting zIndexInOverlay to 1f, we can ensure this
                        // FAB is rendered on top of the shared elements.
                        zIndexInOverlay = 1f
                    ),
            onClick = {}
        ) {
            Icon(Icons.Default.Favorite, contentDescription = "favorite")
        }
    }
}

scaleInSharedContentToBounds

open fun scaleInSharedContentToBounds(
    contentScale: ContentScale = ContentScale.Fit,
    alignment: Alignment = Alignment.Center
): EnterTransition

scaleOutSharedContentToBounds

open fun scaleOutSharedContentToBounds(
    contentScale: ContentScale = ContentScale.Fit,
    alignment: Alignment = Alignment.Center
): ExitTransition

sharedBounds

fun Modifier.sharedBounds(
    sharedContentState: SharedTransitionScope.SharedContentState,
    animatedVisibilityScope: AnimatedVisibilityScope,
    enter: EnterTransition = fadeIn(),
    exit: ExitTransition = fadeOut(),
    boundsTransform: BoundsTransform = DefaultBoundsTransform,
    resizeMode: SharedTransitionScope.ResizeMode = ScaleToBounds(ContentScale.FillWidth, Center),
    placeHolderSize: SharedTransitionScope.PlaceHolderSize = contentSize,
    renderInOverlayDuringTransition: Boolean = true,
    zIndexInOverlay: Float = 0.0f,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip = ParentClip
): Modifier

sharedBounds is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared bounds of the same key share the animated and continuously changing bounds during the layout change. The bounds will be animated from the initial bounds defined by the exiting shared bounds to the target bounds calculated based on the incoming shared shared bounds. The animation for the bounds can be customized using boundsTransform. The target bounds for sharedBounds are determined by the bounds of the sharedBounds becoming visible based on the target state of animatedVisibilityScope.

In contrast to sharedElement, sharedBounds is designed for shared content that has the visually different content. While the sharedBounds keeps the continuity of the bounds, the incoming and outgoing content within the sharedBounds will enter and exit in an enter/exit transition using enter/exit. By default, fadeIn and fadeOut are used to fade the content in or out.

resizeMode defines how the child layout of sharedBounds should be resized during boundsTransform. By default, ScaleToBounds will be used to measure the child content with lookahead constraints to arrive at the stable layout. Then the stable layout will be scaled to fit or fill (depending on the content scale used) the transforming bounds of sharedBounds. If there's a need to relayout content (rather than scaling) based on the animated bounds size (e.g. dynamically resizing a Row), it's recommended to use RemeasureToBounds as the resizeMode.

Important: When a shared bounds finds its match and starts a transition, it will be rendered into the overlay of the SharedTransitionScope in order to avoid being faded in/out along with its parents or clipped by its parent as it transforms to the target size and position. This also means that any clipping or fading for the shared elements will need to be applied explicitly as the child of sharedBounds (i.e. after sharedBounds modifier in the modifier chain). For example: Modifier.sharedBounds(...).clip(shape = RoundedCornerShape(20.dp))

By default, the sharedBounds is clipped by the clipInOverlayDuringTransition of its parent sharedBounds in the layout tree. If the sharedBounds has no parent sharedBounds or if the parent sharedBounds has no clipping defined, it'll not be clipped. If additional clipping is desired to ensure child sharedBounds or child sharedElement don't move outside of the this sharedBounds's visual bounds in the overlay, clipInOverlayDuringTransition can be used to specify the clipping.

While the shared bounds are rendered in overlay during the transition, its zIndexInOverlay can be specified to allow them to render in a different order than their placement/zOrder when not in the overlay. For example, the title of a page is typically placed and rendered before the content below. During the transition, it may be desired to animate the title over on top of the other shared elements on that page to indicate significance or a point of interest. zIndexInOverlay can be used to facilitate such use cases. zIndexInOverlay is 0f by default.

renderInOverlayDuringTransition is true by default. In some rare use cases, there may be no clipping or layer transform (fade, scale, etc) in the application that prevents shared elements from transitioning from one bounds to another without any clipping or sudden alpha change. In such cases, renderInOverlayDuringTransition could be specified to false.

During a shared bounds transition, the space that was occupied by the exiting shared bounds and the space that the entering shared bounds will take up are considered place holders. Their sizes during the shared element transition can be configured through placeHolderSize. By default, it will be the same as the content size of the respective shared bounds. It can also be set to animatedSize or any other PlaceHolderSize to report to their parent layout an animated size to create a visual effect where the parent layout dynamically adjusts the layout to accommodate the animated size of the shared elements.

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// This is the Image that we will add shared element modifier on. It's important to make sure
// modifiers that are not shared between the two shared elements (such as size modifiers if
// the size changes) are the parents (i.e. on the left side) of Modifier.sharedElement.
// Meanwhile, the modifiers that are shared between the shared elements (e.g. Modifier.clip
// in this case) are on the right side of the Modifier.sharedElement.
@Composable
fun Cat(modifier: Modifier = Modifier) {
    Image(
        painterResource(id = R.drawable.yt_profile),
        contentDescription = "cute cat",
        contentScale = ContentScale.FillHeight,
        modifier = modifier.clip(shape = RoundedCornerShape(10))
    )
}

// Shared element key is of type `Any`, which means it can be id, string, etc. The only
// requirement for the key is that it should be the same for shared elements that you intend
// to match. Here we use the image resource id as the key.
val sharedElementKey = R.drawable.yt_profile
var showLargeImage by remember { mutableStateOf(true) }

// First, we need to create a SharedTransitionLayout, this Layout will provide the coordinator
// space for shared element position animation, as well as an overlay for shared elements to
// render in. Children content in this Layout will be able to create shared element transition
// using the receiver scope: SharedTransitionScope
SharedTransitionLayout(
    Modifier.clickable { showLargeImage = !showLargeImage }.fillMaxSize().padding(10.dp)
) {
    // In the SharedTransitionLayout, we will be able to access the receiver scope (i.e.
    // SharedTransitionScope) in order to create shared element transition.
    AnimatedContent(targetState = showLargeImage) { showLargeImageMode ->
        if (showLargeImageMode) {
            Cat(
                Modifier.fillMaxSize()
                    .aspectRatio(1f)
                    // Creating a shared element. Note that this modifier is *after*
                    // the size modifier and aspectRatio modifier, because those size specs
                    // are not shared between the two shared elements.
                    .sharedElement(
                        rememberSharedContentState(sharedElementKey),
                        // Using the AnimatedVisibilityScope from the AnimatedContent
                        // defined above.
                        this@AnimatedContent,
                    )
            )
            Text(
                "Cute Cat YT",
                fontSize = 40.sp,
                color = Color.Blue,
                // Prefer Modifier.sharedBounds for text, unless the texts in both initial
                // content and target content are exactly the same (i.e. same
                // size/font/color)
                modifier =
                    Modifier.fillMaxWidth()
                        // IMPORTANT: Prefer using wrapContentWidth/wrapContentSize over
                        // textAlign
                        // for shared text transition. This allows the layout system sees actual
                        // position and size of the text to facilitate bounds animation.
                        .wrapContentWidth(Alignment.CenterHorizontally)
                        .sharedBounds(
                            rememberSharedContentState(key = "text"),
                            this@AnimatedContent
                        )
            )
        } else {
            Column {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Cat(
                        Modifier.size(100.dp)
                            // Creating another shared element with the same key.
                            // Note that this modifier is *after* the size modifier,
                            // The size changes between these two shared elements, i.e. the size
                            // is not shared between the two shared elements.
                            .sharedElement(
                                rememberSharedContentState(sharedElementKey),
                                this@AnimatedContent,
                            )
                    )
                    Text(
                        "Cute Cat YT",
                        // Change text color & size
                        fontSize = 20.sp,
                        color = Color.DarkGray,
                        // Prefer Modifier.sharedBounds for text, unless the texts in both
                        // initial content and target content are exactly the same (i.e. same
                        // size/font/color)
                        modifier =
                            Modifier
                                // The modifier that is not a part of the shared content, but
                                // rather
                                // for positioning and sizes should be on the *left* side of
                                // sharedBounds/sharedElement.
                                .padding(start = 20.dp)
                                .sharedBounds(
                                    // Here we use a string-based key, in contrast to the key
                                    // above.
                                    rememberSharedContentState(key = "text"),
                                    this@AnimatedContent
                                )
                    )
                }
                Box(
                    Modifier.fillMaxWidth()
                        .height(100.dp)
                        .background(Color(0xffffcc5c), RoundedCornerShape(5.dp))
                )
                Box(
                    Modifier.fillMaxWidth()
                        .height(100.dp)
                        .background(Color(0xff2a9d84), RoundedCornerShape(5.dp))
                )
            }
        }
    }
}

Since sharedBounds show both incoming and outgoing content in its bounds, it affords opportunities to do interesting transitions where additional sharedElement and sharedBounds can be nested in a parent sharedBounds. See the sample code below for a more complex example with nested shared bounds/elements.

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeightIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.Create
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Nested shared bounds sample.
val selectionColor = Color(0xff3367ba)
var expanded by remember { mutableStateOf(true) }
SharedTransitionLayout(
    Modifier.fillMaxSize().clickable { expanded = !expanded }.background(Color(0x88000000))
) {
    AnimatedVisibility(
        visible = expanded,
        enter = EnterTransition.None,
        exit = ExitTransition.None
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            Surface(
                Modifier.align(Alignment.BottomCenter)
                    .padding(20.dp)
                    .sharedBounds(
                        rememberSharedContentState(key = "container"),
                        this@AnimatedVisibility
                    )
                    .requiredHeightIn(max = 60.dp),
                shape = RoundedCornerShape(50),
            ) {
                Row(
                    Modifier.padding(10.dp)
                        // By using Modifier.skipToLookaheadSize(), we are telling the layout
                        // system to layout the children of this node as if the animations had
                        // all finished. This avoid re-laying out the Row with animated width,
                        // which is _sometimes_ desirable. Try removing this modifier and
                        // observe the effect.
                        .skipToLookaheadSize()
                ) {
                    Icon(
                        Icons.Outlined.Share,
                        contentDescription = "Share",
                        modifier =
                            Modifier.padding(
                                top = 10.dp,
                                bottom = 10.dp,
                                start = 10.dp,
                                end = 20.dp
                            )
                    )
                    Icon(
                        Icons.Outlined.Favorite,
                        contentDescription = "Favorite",
                        modifier =
                            Modifier.padding(
                                top = 10.dp,
                                bottom = 10.dp,
                                start = 10.dp,
                                end = 20.dp
                            )
                    )
                    Icon(
                        Icons.Outlined.Create,
                        contentDescription = "Create",
                        tint = Color.White,
                        modifier =
                            Modifier.sharedBounds(
                                    rememberSharedContentState(key = "icon_background"),
                                    this@AnimatedVisibility
                                )
                                .background(selectionColor, RoundedCornerShape(50))
                                .padding(
                                    top = 10.dp,
                                    bottom = 10.dp,
                                    start = 20.dp,
                                    end = 20.dp
                                )
                                .sharedElement(
                                    rememberSharedContentState(key = "icon"),
                                    this@AnimatedVisibility
                                )
                    )
                }
            }
        }
    }
    AnimatedVisibility(
        visible = !expanded,
        enter = EnterTransition.None,
        exit = ExitTransition.None
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            Surface(
                Modifier.align(Alignment.BottomEnd)
                    .padding(30.dp)
                    .sharedBounds(
                        rememberSharedContentState(key = "container"),
                        this@AnimatedVisibility,
                        enter = EnterTransition.None,
                    )
                    .sharedBounds(
                        rememberSharedContentState(key = "icon_background"),
                        this@AnimatedVisibility,
                        enter = EnterTransition.None,
                        exit = ExitTransition.None
                    ),
                shape = RoundedCornerShape(30.dp),
                color = selectionColor
            ) {
                Icon(
                    Icons.Outlined.Create,
                    contentDescription = "Create",
                    tint = Color.White,
                    modifier =
                        Modifier.padding(30.dp)
                            .size(40.dp)
                            .sharedElement(
                                rememberSharedContentState(key = "icon"),
                                this@AnimatedVisibility
                            )
                )
            }
        }
    }
}
See also
sharedBounds

sharedElement

fun Modifier.sharedElement(
    sharedContentState: SharedTransitionScope.SharedContentState,
    animatedVisibilityScope: AnimatedVisibilityScope,
    boundsTransform: BoundsTransform = DefaultBoundsTransform,
    placeHolderSize: SharedTransitionScope.PlaceHolderSize = contentSize,
    renderInOverlayDuringTransition: Boolean = true,
    zIndexInOverlay: Float = 0.0f,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip = ParentClip
): Modifier

sharedElement is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared elements of the same key share the animated and continuously changing bounds during the layout change. The bounds will be animated from the initial bounds defined by the exiting shared element to the target bounds calculated based on the incoming shared element. The animation for the bounds can be customized using boundsTransform. During the bounds transform, sharedElement will re-measure and relayout its child layout using fixed constraints derived from its animated size, similar to RemeasureToBounds resizeMode in sharedBounds.

In contrast to sharedBounds, sharedElement is designed for shared content that has the exact match in terms of visual content and layout when the measure constraints are the same. Such examples include image assets, icons, MovableContent etc. Only the shared element that is becoming visible will be rendered during the transition. The bounds for shared element are determined by the bounds of the shared element becoming visible based on the target state of animatedVisibilityScope.

Important: When a shared element finds its match and starts a transition, it will be rendered into the overlay of the SharedTransitionScope in order to avoid being faded in/out along with its parents or clipped by its parent as it transforms to the target size and position. This also means that any clipping or fading for the shared elements will need to be applied explicitly as the child of sharedElement (i.e. after sharedElement modifier in the modifier chain). For example: Modifier.sharedElement(...).clip(shape = RoundedCornerShape(20.dp)).animateEnterExit(...)

By default, the sharedElement is clipped by the clipInOverlayDuringTransition of its parent sharedBounds. If the sharedElement has no parent sharedBounds or if the parent sharedBounds has no clipping defined, it'll not be clipped. If additional clipping is desired to ensure sharedElement doesn't move outside of a visual bounds, clipInOverlayDuringTransition can be used to specify the clipping for when the shared element is going through an active transition towards a new target bounds.

While the shared elements are rendered in overlay during the transition, its zIndexInOverlay can be specified to allow shared elements to render in a different order than their placement/zOrder when not in the overlay. For example, the title of a page is typically placed and rendered before the content below. During the transition, it may be desired to animate the title over on top of the other shared elements on that page to indicate significance or a point of interest. zIndexInOverlay can be used to facilitate such use cases. zIndexInOverlay is 0f by default.

renderInOverlayDuringTransition is true by default. In some rare use cases, there may be no clipping or layer transform (fade, scale, etc) in the application that prevents shared elements from transitioning from one bounds to another without any clipping or sudden alpha change. In such cases, renderInOverlayDuringTransition could be specified to false.

During a shared element transition, the space that was occupied by the exiting shared element and the space that the entering shared element will take up are considered place holders. Their sizes during the shared element transition can be configured through placeHolderSize. By default, it will be the same as the content size of the respective shared element. It can also be set to animatedSize or any other PlaceHolderSize to report to their parent layout an animated size to create a visual effect where the parent layout dynamically adjusts the layout to accommodate the animated size of the shared elements.

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// This is the Image that we will add shared element modifier on. It's important to make sure
// modifiers that are not shared between the two shared elements (such as size modifiers if
// the size changes) are the parents (i.e. on the left side) of Modifier.sharedElement.
// Meanwhile, the modifiers that are shared between the shared elements (e.g. Modifier.clip
// in this case) are on the right side of the Modifier.sharedElement.
@Composable
fun Cat(modifier: Modifier = Modifier) {
    Image(
        painterResource(id = R.drawable.yt_profile),
        contentDescription = "cute cat",
        contentScale = ContentScale.FillHeight,
        modifier = modifier.clip(shape = RoundedCornerShape(10))
    )
}

// Shared element key is of type `Any`, which means it can be id, string, etc. The only
// requirement for the key is that it should be the same for shared elements that you intend
// to match. Here we use the image resource id as the key.
val sharedElementKey = R.drawable.yt_profile
var showLargeImage by remember { mutableStateOf(true) }

// First, we need to create a SharedTransitionLayout, this Layout will provide the coordinator
// space for shared element position animation, as well as an overlay for shared elements to
// render in. Children content in this Layout will be able to create shared element transition
// using the receiver scope: SharedTransitionScope
SharedTransitionLayout(
    Modifier.clickable { showLargeImage = !showLargeImage }.fillMaxSize().padding(10.dp)
) {
    // In the SharedTransitionLayout, we will be able to access the receiver scope (i.e.
    // SharedTransitionScope) in order to create shared element transition.
    AnimatedContent(targetState = showLargeImage) { showLargeImageMode ->
        if (showLargeImageMode) {
            Cat(
                Modifier.fillMaxSize()
                    .aspectRatio(1f)
                    // Creating a shared element. Note that this modifier is *after*
                    // the size modifier and aspectRatio modifier, because those size specs
                    // are not shared between the two shared elements.
                    .sharedElement(
                        rememberSharedContentState(sharedElementKey),
                        // Using the AnimatedVisibilityScope from the AnimatedContent
                        // defined above.
                        this@AnimatedContent,
                    )
            )
            Text(
                "Cute Cat YT",
                fontSize = 40.sp,
                color = Color.Blue,
                // Prefer Modifier.sharedBounds for text, unless the texts in both initial
                // content and target content are exactly the same (i.e. same
                // size/font/color)
                modifier =
                    Modifier.fillMaxWidth()
                        // IMPORTANT: Prefer using wrapContentWidth/wrapContentSize over
                        // textAlign
                        // for shared text transition. This allows the layout system sees actual
                        // position and size of the text to facilitate bounds animation.
                        .wrapContentWidth(Alignment.CenterHorizontally)
                        .sharedBounds(
                            rememberSharedContentState(key = "text"),
                            this@AnimatedContent
                        )
            )
        } else {
            Column {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Cat(
                        Modifier.size(100.dp)
                            // Creating another shared element with the same key.
                            // Note that this modifier is *after* the size modifier,
                            // The size changes between these two shared elements, i.e. the size
                            // is not shared between the two shared elements.
                            .sharedElement(
                                rememberSharedContentState(sharedElementKey),
                                this@AnimatedContent,
                            )
                    )
                    Text(
                        "Cute Cat YT",
                        // Change text color & size
                        fontSize = 20.sp,
                        color = Color.DarkGray,
                        // Prefer Modifier.sharedBounds for text, unless the texts in both
                        // initial content and target content are exactly the same (i.e. same
                        // size/font/color)
                        modifier =
                            Modifier
                                // The modifier that is not a part of the shared content, but
                                // rather
                                // for positioning and sizes should be on the *left* side of
                                // sharedBounds/sharedElement.
                                .padding(start = 20.dp)
                                .sharedBounds(
                                    // Here we use a string-based key, in contrast to the key
                                    // above.
                                    rememberSharedContentState(key = "text"),
                                    this@AnimatedContent
                                )
                    )
                }
                Box(
                    Modifier.fillMaxWidth()
                        .height(100.dp)
                        .background(Color(0xffffcc5c), RoundedCornerShape(5.dp))
                )
                Box(
                    Modifier.fillMaxWidth()
                        .height(100.dp)
                        .background(Color(0xff2a9d84), RoundedCornerShape(5.dp))
                )
            }
        }
    }
}
See also
sharedBounds

sharedElementWithCallerManagedVisibility

fun Modifier.sharedElementWithCallerManagedVisibility(
    sharedContentState: SharedTransitionScope.SharedContentState,
    visible: Boolean,
    boundsTransform: BoundsTransform = DefaultBoundsTransform,
    placeHolderSize: SharedTransitionScope.PlaceHolderSize = contentSize,
    renderInOverlayDuringTransition: Boolean = true,
    zIndexInOverlay: Float = 0.0f,
    clipInOverlayDuringTransition: SharedTransitionScope.OverlayClip = ParentClip
): Modifier

sharedElementWithCallerManagedVisibility is a modifier that tags a layout with a SharedContentState.key, such that entering and exiting shared elements of the same key share the animated and continuously changing bounds during the layout change. The bounds will be animated from the initial bounds defined by the exiting shared element to the target bounds calculated based on the incoming shared element. The animation for the bounds can be customized using boundsTransform.

Compared to sharedElement, sharedElementWithCallerManagedVisibility is designed for shared element transitions where the shared element is not a part of the content that is being animated out by AnimatedVisibility. Therefore, it is the caller's responsibility to explicitly remove the exiting shared element (i.e. shared elements where visible == false) from the tree as appropriate. Typically this is when the transition is finished (i.e. SharedTransitionScope.isTransitionActive == false). The target bounds is derived from the sharedElementWithCallerManagedVisibility with visible being true.

In contrast to sharedBounds, this modifier is intended for shared content that has the exact match in terms of visual content and layout when the measure constraints are the same. Such examples include image assets, icons, MovableContent etc. Only the shared element that is becoming visible will be rendered during the transition.

Important: When a shared element finds its match and starts a transition, it will be rendered into the overlay of the SharedTransitionScope in order to avoid being faded in/out along with its parents or clipped by its parent as it transforms to the target size and position. This also means that any clipping or fading for the shared elements will need to be applied explicitly as the child of sharedElementWithCallerManagedVisibility (i.e. after sharedElementWithCallerManagedVisibility modifier in the modifier chain). For example:

Modifier.sharedElementWithCallerManagedVisibility(...)
.clip(shape = RoundedCornerShape(20.dp))

By default, the sharedElementWithCallerManagedVisibility is clipped by the clipInOverlayDuringTransition of its parent sharedBounds. If the sharedElementWithCallerManagedVisibility has no parent sharedBounds or if the parent sharedBounds has no clipping defined, it'll not be clipped. If additional clipping is desired to ensure sharedElementWithCallerManagedVisibility doesn't move outside of a visual bounds, clipInOverlayDuringTransition can be used to specify the clipping for when the shared element is going through an active transition towards a new target bounds.

While the shared elements are rendered in overlay during the transition, its zIndexInOverlay can be specified to allow shared elements to render in a different order than their placement/zOrder when not in the overlay. For example, the title of a page is typically placed and rendered before the content below. During the transition, it may be desired to animate the title over on top of the other shared elements on that page to indicate significance or a point of interest. zIndexInOverlay can be used to facilitate such use cases. zIndexInOverlay is 0f by default.

renderInOverlayDuringTransition is true by default. In some rare use cases, there may be no clipping or layer transform (fade, scale, etc) in the application that prevents shared elements from transitioning from one bounds to another without any clipping or sudden alpha change. In such cases, renderInOverlayDuringTransition could be specified to false.

During a shared element transition, the space that was occupied by the exiting shared element and the space that the entering shared element will take up are considered place holders. Their sizes during the shared element transition can be configured through placeHolderSize. By default, it will be the same as the content size of the respective shared element. It can also be set to animatedSize or any other PlaceHolderSize to report to their parent layout an animated size to create a visual effect where the parent layout dynamically adjusts the layout to accommodate the animated size of the shared elements.

import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

var showThumbnail by remember { mutableStateOf(true) }
val movableContent = remember {
    movableContentOf {
        val cornerRadius = animateDpAsState(targetValue = if (!showThumbnail) 20.dp else 5.dp)
        Image(
            painterResource(id = R.drawable.yt_profile),
            contentDescription = "cute cat",
            contentScale = ContentScale.FillHeight,
            modifier = Modifier.clip(shape = RoundedCornerShape(cornerRadius.value))
        )
    }
}
SharedTransitionLayout(
    Modifier.clickable { showThumbnail = !showThumbnail }.fillMaxSize().padding(10.dp)
) {
    Column {
        Box(
            // When using Modifier.sharedElementWithCallerManagedVisibility(), even when
            // visible == false, the layout will continue to occupy space in its parent layout.
            // The content will continue to be composed, unless the content is [MovableContent]
            // like in this example below.
            Modifier.sharedElementWithCallerManagedVisibility(
                    rememberSharedContentState(key = "YT"),
                    showThumbnail,
                )
                .size(100.dp)
        ) {
            if (showThumbnail) {
                movableContent()
            }
        }
        Box(
            Modifier.fillMaxWidth()
                .height(100.dp)
                .background(Color(0xffffcc5c), RoundedCornerShape(5.dp))
        )
        Box(
            Modifier.fillMaxWidth()
                .height(100.dp)
                .background(Color(0xff2a9d84), RoundedCornerShape(5.dp))
        )
    }
    Box(
        Modifier.fillMaxSize()
            .aspectRatio(1f)
            .sharedElementWithCallerManagedVisibility(
                rememberSharedContentState(key = "YT"),
                !showThumbnail
            )
    ) {
        if (!showThumbnail) {
            movableContent()
        }
    }
}

skipToLookaheadSize

fun Modifier.skipToLookaheadSize(): Modifier

skipToLookaheadSize enables a layout to measure its child with the lookahead constraints, therefore laying out the child as if the transition has finished. This is particularly helpful for layouts where re-flowing content based on animated constraints is undesirable, such as texts.

In the sample below, try remove the skipToLookaheadSize modifier and observe the difference:

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeightIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.Create
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.Share
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Nested shared bounds sample.
val selectionColor = Color(0xff3367ba)
var expanded by remember { mutableStateOf(true) }
SharedTransitionLayout(
    Modifier.fillMaxSize().clickable { expanded = !expanded }.background(Color(0x88000000))
) {
    AnimatedVisibility(
        visible = expanded,
        enter = EnterTransition.None,
        exit = ExitTransition.None
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            Surface(
                Modifier.align(Alignment.BottomCenter)
                    .padding(20.dp)
                    .sharedBounds(
                        rememberSharedContentState(key = "container"),
                        this@AnimatedVisibility
                    )
                    .requiredHeightIn(max = 60.dp),
                shape = RoundedCornerShape(50),
            ) {
                Row(
                    Modifier.padding(10.dp)
                        // By using Modifier.skipToLookaheadSize(), we are telling the layout
                        // system to layout the children of this node as if the animations had
                        // all finished. This avoid re-laying out the Row with animated width,
                        // which is _sometimes_ desirable. Try removing this modifier and
                        // observe the effect.
                        .skipToLookaheadSize()
                ) {
                    Icon(
                        Icons.Outlined.Share,
                        contentDescription = "Share",
                        modifier =
                            Modifier.padding(
                                top = 10.dp,
                                bottom = 10.dp,
                                start = 10.dp,
                                end = 20.dp
                            )
                    )
                    Icon(
                        Icons.Outlined.Favorite,
                        contentDescription = "Favorite",
                        modifier =
                            Modifier.padding(
                                top = 10.dp,
                                bottom = 10.dp,
                                start = 10.dp,
                                end = 20.dp
                            )
                    )
                    Icon(
                        Icons.Outlined.Create,
                        contentDescription = "Create",
                        tint = Color.White,
                        modifier =
                            Modifier.sharedBounds(
                                    rememberSharedContentState(key = "icon_background"),
                                    this@AnimatedVisibility
                                )
                                .background(selectionColor, RoundedCornerShape(50))
                                .padding(
                                    top = 10.dp,
                                    bottom = 10.dp,
                                    start = 20.dp,
                                    end = 20.dp
                                )
                                .sharedElement(
                                    rememberSharedContentState(key = "icon"),
                                    this@AnimatedVisibility
                                )
                    )
                }
            }
        }
    }
    AnimatedVisibility(
        visible = !expanded,
        enter = EnterTransition.None,
        exit = ExitTransition.None
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            Surface(
                Modifier.align(Alignment.BottomEnd)
                    .padding(30.dp)
                    .sharedBounds(
                        rememberSharedContentState(key = "container"),
                        this@AnimatedVisibility,
                        enter = EnterTransition.None,
                    )
                    .sharedBounds(
                        rememberSharedContentState(key = "icon_background"),
                        this@AnimatedVisibility,
                        enter = EnterTransition.None,
                        exit = ExitTransition.None
                    ),
                shape = RoundedCornerShape(30.dp),
                color = selectionColor
            ) {
                Icon(
                    Icons.Outlined.Create,
                    contentDescription = "Create",
                    tint = Color.White,
                    modifier =
                        Modifier.padding(30.dp)
                            .size(40.dp)
                            .sharedElement(
                                rememberSharedContentState(key = "icon"),
                                this@AnimatedVisibility
                            )
                )
            }
        }
    }
}

Public properties

isTransitionActive

val isTransitionActiveBoolean

Indicates whether there is any ongoing transition between matched sharedElement or sharedBounds.