| # SceneTransitionLayout | |
| ## Summary | |
| `SceneTransitionLayout` is a container that will animate its content for you | |
| when that content changes. It displays the current *scene* and will animate the | |
| *elements* of each scene during transitions. *Shared elements* (UI elements | |
| shared across two scenes) will automatically morph from their state in the | |
| current scene to their state in the target scene and the other elements can be | |
| animated in & out using simple [*transformations*](#transformations) like fades | |
| or translations. | |
| ## Adding `SceneTransitionLayout` to your code | |
| The first step is to introduce `SceneTransitionLayout` in your UI and define the | |
| different scenes that we are going to transition to. We can also define the | |
| *user actions* of each scene to define what happens when the user swipes or | |
| triggers the back gesture. | |
| Each scene is identified by a unique | |
| [SceneKey](src/com/android/compose/animation/scene/Key.kt). This key is used to | |
| define the content of each scene as well as defining the user actions to and | |
| from that scene. | |
| ```kotlin | |
| /** The different scenes of this layout/container. */ | |
| object Scenes { | |
| val Foo = SceneKey(debugName = "Foo") | |
| val Bar = SceneKey(debugName = "Bar") | |
| } | |
| @Composable | |
| fun SceneTransitionLayoutDemo(modifier: Modifier = Modifier) { | |
| // The current scene. Changing this value will automatically animate between | |
| // scenes. | |
| val state = remember { | |
| MutableSceneTransitionLayoutState( | |
| Scenes.Foo, | |
| // TODO: Define the transitions between scenes. | |
| transitions = transitions {}, | |
| ) | |
| } | |
| SceneTransitionLayout(state, modifier) { | |
| // The list of scenes. Note that the order is important, and during | |
| // transitions the first defined scene will be drawn below the second, | |
| // scene, which will be drawn below the third one, etc. | |
| // The Foo scene. Swiping down from Foo brings us to Bar. | |
| scene(Scenes.Foo, userActions = mapOf(Swipe.Down to Scenes.Bar)) { Foo() } | |
| // The Bar scene. Swiping up from Bar or going back brings us to Foo. | |
| scene( | |
| Scenes.Bar, | |
| userActions = mapOf(Swipe.Up to Scenes.Foo, Back to Scenes.Foo), | |
| ) { | |
| Bar() | |
| } | |
| } | |
| } | |
| ``` | |
| ## Marking (shared) elements {#elements} | |
| The `SceneTransitionLayout.scene()` builder provides you with a `ContentScope` | |
| to **mark elements, using `Modifier.element(ElementKey)`**. Marking elements | |
| will have 2 side effects: | |
| 1. *Shared elements* are automatically moved and resized for you when | |
| transitioning from one scene to another. | |
| 2. *Transformations* can be applied to elements that are not shared between | |
| scenes during a *transition*, using the [transition DSL](#transitions). | |
| In the following snippet, we define 2 elements `GreenSquare` and `BlueCircle` | |
| that are shared between the `Foo` and `Bar` scenes, i.e. they are present in | |
| both those scenes. Both elements have different sizes and positions in each | |
| scene, which are automatically animated for you when going from one scene to the | |
| other. | |
| {height="200"} | |
| ```kotlin | |
| object Elements { | |
| val GreenSquare = ElementKey(debugName = "GreenSquare") | |
| val BlueCircle = ElementKey(debugName = "BlueCircle") | |
| } | |
| @Composable | |
| fun ContentScope.Foo(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| GreenSquare(size = 100.dp, Modifier.align(Alignment.TopStart)) | |
| BlueCircle(size = 70.dp, Modifier.align(Alignment.TopEnd)) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.Bar(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| GreenSquare(size = 70.dp, Modifier.align(Alignment.TopEnd)) | |
| BlueCircle(size = 100.dp, Modifier.align(Alignment.BottomEnd)) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.GreenSquare(size: Dp, modifier: Modifier = Modifier) { | |
| Box(modifier.element(Elements.GreenSquare).size(size).background(Color.Green)) | |
| } | |
| @Composable | |
| fun ContentScope.BlueCircle(size: Dp, modifier: Modifier = Modifier) { | |
| Box(modifier.element(Elements.BlueCircle).size(size).background(Color.Blue, CircleShape)) | |
| } | |
| ``` | |
| ## Animating shared values {#shared-values} | |
| Marking elements will already animate their size and position when transitioning | |
| between scenes, but sometimes you will also need to animate other types of | |
| element properties like background color, background radius, or any other kind | |
| of interpolable values. In those cases, you should use | |
| `ContentScope.animateContent(Color|Dp|...)AsState()` (if you are animating a | |
| value associated to a scene or overlay) or | |
| `ElementScope.animateElement(Color|Dp|...)AsState()` (if you are animating a | |
| value associated to an element) to automatically animate/interpolate any kind of | |
| shared values. | |
| **Tip:** Even if your UI is rendered by a `View` inside an | |
| [AndroidView](https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose), | |
| you can and should still use `animateSharedXAsState()` to animate the `View` | |
| properties. **Whenever you catch yourself manually interpolating values | |
| depending on a progress, try to replace that by`animateSharedXAsState()` | |
| instead.** | |
| To animate an element value, you will have to replace your calls to | |
| `Modifier.element(key)` by a call to the `ContentScope.Element(key)` composable | |
| instead: | |
| ```kotlin | |
| // Before: | |
| @Composable fun ContentScope.SharedElement(modifier: Modifier = Modifier) { | |
| Box(modifier.element(Elements.SharedElement)) { /* Element content here. */ } | |
| } | |
| // After: | |
| @Composable fun ContentScope.SharedElement(color: Color, modifier: Modifier = Modifier) { | |
| Element(Elements.SharedElement, modifier) { | |
| /* | |
| * Animated values here. | |
| * | |
| * Important: Never read those values during composition, otherwise an | |
| * exception will be thrown. | |
| */ | |
| val animatedColor by animateElementColorAsState(color, SharedValues.SharedElementColor) | |
| content { | |
| /* Element content here. */ | |
| Box(Modifier.drawBehind { drawRect(animatedColor) }) | |
| } | |
| } | |
| } | |
| ``` | |
| **Important:** You should **never read animated values during composition**, and | |
| an exception will be thrown if you do. Instead, make sure to read those values | |
| during the layout or drawing phase. | |
| See the example below that illustrates how you can animate the size, radius, | |
| color and even text of a shared element. | |
| {height="200"} | |
| ```kotlin | |
| object Elements { | |
| val SharedElement = ElementKey("SharedElement") | |
| } | |
| object SharedValues { | |
| val SharedElementRadius = ValueKey("SharedElementCornerRadius") | |
| val SharedElementColor = ValueKey("SharedElementColor") | |
| val SharedElementValue = ValueKey("SharedElementValue") | |
| } | |
| @Composable | |
| fun ContentScope.Foo(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| SharedElement( | |
| size = 90.dp, | |
| radius = 30.dp, | |
| color = Color.Red, | |
| value = 20, | |
| Modifier.align(Alignment.TopStart), | |
| ) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.Bar(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| SharedElement( | |
| size = 140.dp, | |
| radius = 15.dp, | |
| color = Color.Green, | |
| value = 80, | |
| Modifier.align(Alignment.BottomEnd), | |
| ) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.SharedElement( | |
| size: Dp, | |
| radius: Dp, | |
| color: Color, | |
| value: Int, | |
| modifier: Modifier = Modifier, | |
| ) { | |
| Element(Elements.SharedElement, modifier.size(size)) { | |
| val animatedRadius by animateElementDpAsState(radius, SharedValues.SharedElementRadius) | |
| val animatedColor by animateElementColorAsState(color, SharedValues.SharedElementColor) | |
| val animatedValue by animateElementIntAsState(value, SharedValues.SharedElementValue) | |
| content { | |
| Box( | |
| Modifier.fillMaxSize().drawBehind { | |
| val cornerRadius = CornerRadius(animatedRadius.toPx()) | |
| drawRoundRect(animatedColor, cornerRadius = cornerRadius) | |
| }, | |
| contentAlignment = Alignment.Center, | |
| ) { | |
| // Important: we can't read animated values during composition, so instead of | |
| // computing the text to draw during composition, we postpone that to the layout | |
| // phase. The AnimatedText composable here is left as an example, but you should | |
| // probably never have to do something like this in production code. | |
| AnimatedText(text = { "Value=$animatedValue" }) | |
| } | |
| } | |
| } | |
| } | |
| // Important: Don't copy paste this in your production code. | |
| @Composable | |
| private fun AnimatedText(text: () -> String, modifier: Modifier = Modifier) { | |
| val textMeasurer = rememberTextMeasurer() | |
| val lastLayoutResult = remember { | |
| object { | |
| var result: TextLayoutResult? = null | |
| } | |
| } | |
| Layout(modifier.drawBehind { drawText(lastLayoutResult.result!!) }) { _, _ -> | |
| val layoutResult = textMeasurer.measure(text()) | |
| lastLayoutResult.result = layoutResult | |
| layout(layoutResult.size.width, layoutResult.size.height) {} | |
| } | |
| } | |
| ``` | |
| ## Movable elements | |
| **Tip:** If you don't know whether you should use `MovableElement`, it probably | |
| means that you don't and you can skip this section. | |
| By default, you should use the `Modifier.element(key)` or | |
| `ContentScope.Element(key)` APIs to mark elements. These APIs are the most | |
| lightweight and will simply **compose** your elements **in all scenes** they are | |
| in, duplicating elements across scenes, while making sure that shared elements | |
| are **placed and drawn** only **in a single scene** during transitions. This is | |
| a good default that is easy to reason about, but this means that **by default | |
| shared elements are duplicated across scenes and will lose any kind of internal | |
| state when going from one scene to another one**. | |
| Duplicating elements might be expensive for large elements or very inconvenient | |
| for elements with some internal state that is hard to *hoist* in a ViewModel. | |
| For example: | |
| * a media player might have a complex shader animation and it is hard to | |
| extract all the shader state in the player ViewModel; | |
| * you want to create an element from a big legacy `View` but inflating this | |
| `View` in multiple scene is too costly in terms of performance or infeasible | |
| because of assumptions made in that legacy code. | |
| For these use cases, we also provide **the `ContentScope.MovableElement` API to | |
| create elements that are always composed in a single scene and whose internal | |
| state is preserved across scenes**. | |
| > **Tip:** Most of the time, you should still favor the lightweight and simpler | |
| > to use `Modifier.element(key)` or `ContentScope.Element(key)` APIs over | |
| > `ContentScope.MovableElement(key)`, especially if you are dealing with pure | |
| > Compose code. | |
| ### Creating a `MovableElement` | |
| **Important:** Using `MovableElement` will have implications on the correctness | |
| of the transition. Make sure you also follow and understand both | |
| [Picking the composition scene](#movable-element-scene) and | |
| [Size of a `MovableElement`](#movable-element-size). | |
| The API for `MovableElement` is almost the same as the `Element` API described | |
| in [Animating shared values](#shared-values): | |
| {height="200"} | |
| ```kotlin | |
| object Elements { | |
| val SharedMovableElement = | |
| MovableElementKey( | |
| debugName = "SharedMovableElement", | |
| // Note that we have to provide the different contents (scenes or overlays) | |
| // that will contain this movable element. | |
| contentPicker = DefaultElementContentPicker(contents = setOf(Scenes.Foo, Scenes.Bar)), | |
| ) | |
| } | |
| @Composable | |
| fun ContentScope.Foo(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| SharedMovableElement(size = 90.dp, color = Color.Blue) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.Bar(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| SharedMovableElement( | |
| size = 140.dp, | |
| color = Color.Green, | |
| Modifier.align(Alignment.BottomEnd), | |
| ) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.SharedMovableElement(size: Dp, color: Color, modifier: Modifier = Modifier) { | |
| MovableElement(Elements.SharedMovableElement, modifier.size(size)) { | |
| // Animated values here. | |
| val backgroundColor by animateElementColorAsState(color, SharedValues.SharedElementColor) | |
| content { | |
| // Element content here. | |
| // | |
| // Any internal state like transitions, remember-ed objects, etc will be kept across | |
| // scenes. | |
| val circleColor by | |
| rememberInfiniteTransition() | |
| .animateColor( | |
| Color.Blue, | |
| Color.Green, | |
| infiniteRepeatable(tween(3_000), repeatMode = RepeatMode.Reverse) | |
| ) | |
| Box( | |
| Modifier.fillMaxSize().drawBehind { | |
| drawRect(backgroundColor) | |
| drawCircle(circleColor, radius = this.size.minDimension / 3) | |
| } | |
| ) | |
| } | |
| } | |
| } | |
| ``` | |
| **Important:** Make sure that you put the content of your `MovableElement` | |
| inside the `content {}` block! If you don't, your code will still compile but | |
| the content will actually be composed in all scenes. | |
| ### Specifying the elements contents {#movable-element-contents} | |
| The first downside of `MovableElement` is that you should provide a | |
| `StaticElementContentPicker` to help `SceneTransitionLayout` know in which | |
| contents (scenes or overlays) a `MovableElement` will be. | |
| **Important:** Make sure that your `ContentPicker` (any version of the following | |
| sections) does not specify scenes where the `MovableElement` is not present. | |
| This may break animations (especially in use cases with NestedSTLs). To | |
| discourage accumulating scenes on a picker, in most cases you should not share a | |
| picker among multiple elements. | |
| #### Using `MovableElementContentPicker` {#movable-element-picker} | |
| The easiest way to create a picker that will lead to a correct transition for | |
| your `MovableElement` is to use `MovableElementContentPicker`. This picker will | |
| compose your `MovableElement` in the scene we are transitioning to if that scene | |
| is **assumed** to contain your element, otherwise it will compose it in the | |
| scene we are transitioning from. | |
| ```kotlin | |
| object MediaPlayer { | |
| object Elements { | |
| val MediaPlayer = | |
| MovableElementKey( | |
| "MediaPlayer", | |
| contentPicker = | |
| MovableElementContentPicker( | |
| /** The contents in which the media player is in. */ | |
| contents = setOf(Scenes.Lockscreen, Scenes.Shade, Scenes.QuickSettings) | |
| ) | |
| ) | |
| } | |
| } | |
| ``` | |
| If composing your movable element in the scene we are going to does not work for | |
| your use case, for instance because it leads to a incorrect zIndex/layering of | |
| your element, then you will have to use another picker like | |
| `DefaultElementContentPicker`. However, as mentioned in | |
| [Size of a `MovableElement`](#movable-element-size), this means that your | |
| movable element should not wrap its content width or height, otherwise it will | |
| lead to broken animations. | |
| #### Using `DefaultElementContentPicker` | |
| If you need to keep the same default behavior as `Modifier.element()` and always | |
| draw the element in the content with the highest z-index, then you should use | |
| `DefaultElementContentPicker(contents)`. | |
| ```kotlin | |
| object Elements { | |
| val MediaPlayer = | |
| MovableElementKey( | |
| "MediaPlayer", | |
| contentPicker = | |
| DefaultElementContentPicker( | |
| contents = | |
| setOf( | |
| Scenes.Lockscreen, | |
| Scenes.Shade, | |
| Scenes.QuickSettings, | |
| ) | |
| ) | |
| ) | |
| } | |
| ``` | |
| #### Using a custom picker {#element-custom-picker} | |
| Here is an example of how you can implement a custom | |
| `StaticElementContentPicker` for more complex use cases: | |
| ```kotlin | |
| object MediaPlayer { | |
| object Elements { | |
| val MediaPlayer = MovableElementKey("MediaPlayer", contentPicker = MediaPlayerContentPicker) | |
| } | |
| private object MediaPlayerContentPicker : StaticElementContentPicker { | |
| /** The different contents in which the movable Media player can be composed. */ | |
| override val contents = setOf(Scenes.Lockscreen, Scenes.Shade, Scenes.QuickSettings) | |
| override fun contentDuringTransition( | |
| element: ElementKey, | |
| transition: ContentState.Transition<*>, | |
| fromContentZIndex: Float, | |
| toContentZIndex: Float | |
| ): ContentKey { | |
| return when { | |
| // During the Lockscreen => Shade transition, the media player is visible in the | |
| // Lockscreen when progress is in [0; 0.5]. It is then visible in the Shade scene | |
| // when progress is in [0.8; 1]. We move it half-way through, when progress = 0.65. | |
| transition.isTransitioning(from = Scenes.Lockscreen, to = Scenes.Shade) -> { | |
| if (transition.progress < 0.65f) { | |
| Scenes.Lockscreen | |
| } else { | |
| Scenes.Shade | |
| } | |
| } | |
| // Same as Lockscreen => Shade, but with reversed progress. | |
| transition.isTransitioning(from = Scenes.Shade, to = Scenes.Lockscreen) -> { | |
| if (transition.progress < 1f - 0.65f) { | |
| Scenes.Shade | |
| } else { | |
| Scenes.Lockscreen | |
| } | |
| } | |
| // When going from QS <=> Shade we always want to compose the media player in the QS | |
| // scene. | |
| transition.isTransitioningBetween(Scenes.QuickSettings, Scenes.Shade) -> { | |
| Scenes.QuickSettings | |
| } | |
| // We are in a transition between either Lockscreen, Shade or QuickSettings and another | |
| // scene (that shouldn't have the media player). Pick the scene where we know that the | |
| // media player is in. | |
| else -> pickSingleContentIn(contents, transition, element) | |
| } | |
| } | |
| } | |
| } | |
| ``` | |
| ### Size of a `MovableElement` {#movable-element-size} | |
| The second downside of `MovableElement` is that if we never compose an element | |
| in one of the scenes we are transitioning between, then `SceneTransitionLayout` | |
| has no way of knowing the target size of the element in that scene and therefore | |
| might assume an incorrect size during transitions. | |
| For instance, let's say that a `SceneTransitionLayout` is currently idle in | |
| scene `A` and contains a movable element `Foo`. If we start a transition from | |
| scene `A` to scene `B` (which also contains `Foo`) and the | |
| [scene picker](#movable-element-contents) associated to `Foo` returns scene `A`, | |
| then `Foo` will only be composed in scene `B` once the transition is done. | |
| During the transition, `SceneTransitionLayout` will make assumptions on the size | |
| of `Foo` in scene `B` which might be incorrect depending on your use case. | |
| #### Element does not wrap content | |
| If the size of your element does not depend on the size of its content, i.e. it | |
| has either a fixed size or fills its parent size, then everything should work as | |
| expected independently of the [scene picker](#movable-element-scene) | |
| implementation. | |
| ```kotlin {.good} | |
| @Composable | |
| fun ContentScope.Foo(height: Dp, modifier: Modifier = Modifier) { | |
| MovableElement( | |
| Elements.Foo, | |
| // Neither the height and width of this element depend on its content, | |
| // so the size is computable in each scene. | |
| modifier.height(height).fillMaxWidth(), | |
| ) { | |
| content { ... } | |
| } | |
| } | |
| ``` | |
| ```kotlin {.bad} | |
| @Composable | |
| fun ContentScope.Foo(height: Dp, modifier: Modifier = Modifier) { | |
| MovableElement(Elements.Foo, modifier) { | |
| content { | |
| // This won't work as expected because the size of Foo depends on the | |
| // size of its content. | |
| Box(Modifier.height(height).fillMaxWidth()) { ... } | |
| } | |
| } | |
| } | |
| ``` | |
| #### Element size does not change | |
| If the size of your element is the same in all scenes, then it will also work as | |
| expected because by default `SceneTransitionLayout` will assume that the size of | |
| an element does not change across scenes. | |
| ```kotlin {.good} | |
| @Composable | |
| fun ContentScope.Foo(modifier: Modifier = Modifier) { | |
| MovableElement(Elements.Foo, modifier) { | |
| content { | |
| // Foo wraps its content, but the content is always the same size | |
| // independently of the scene in which the element is, so everything | |
| // should work as expected. | |
| Box(Modifier.size(100.dp)) { ... } | |
| } | |
| } | |
| } | |
| ``` | |
| #### Element wraps content with different size | |
| If neither of the two previous sections apply to your use case, then it means | |
| that your element wraps its content width or height and that it will have a | |
| different size in different scenes. | |
| This is the most complex case and you should avoid this situation if you can. | |
| Otherwise, the only way to make this case work (as of July 2024) is to use | |
| [MovableElementContentPicker](#movable-element-picker), which will compose your | |
| movable element in the scene we are transitioning to, which will allow | |
| `SceneTransitionLayout` to know the size of the element in that scene. Given | |
| that `SceneTransitionLayout` will probably have measured your element in the | |
| scene we are transitioning from, then it will be able to correctly interpolate | |
| its size. | |
| **Caveat:** As mentioned in | |
| [Using MovableElementContentPicker](#movable-element-picker), | |
| `MovableElementContentPicker` might break the zIndex/layering of your element. | |
| ## Defining transitions {#transitions} | |
| `SceneTransitionLayout` will automatically morph shared elements between their | |
| state in the source scene and in the destination scene. For elements that are | |
| not shared and either appear or disappear between the scenes, | |
| `SceneTransitionLayout` provides a | |
| [transition DSL](src/com/android/compose/animation/scene/TransitionDsl.kt) to | |
| define the transition and apply *transformations* to these elements during the | |
| transition. | |
| For this section, we will add two new elements: `BlackSquare` in the `Foo` scene | |
| and `RedRect` in the `Bar` scene. Given that those elements are not shared, they | |
| will respectively appear or disappear when transitioning to or from their scene. | |
| We can add *transformations* in the *transition* definition to nicely animate | |
| their (dis)appearance. Let's start with a simple `fade()` that fades these | |
| elements in and out. | |
| {height="200"} | |
| ```kotlin | |
| object Elements { | |
| ... | |
| val BlackSquare = ElementKey("OrangeSquare") | |
| val RedRect = ElementKey("RedRect") | |
| } | |
| @Composable | |
| fun SceneTransitionLayoutDemo(modifier: Modifier = Modifier) { | |
| val state = remember { | |
| MutableSceneTransitionLayoutState( | |
| Scenes.Foo, | |
| transitions = | |
| transitions { | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| fractionRange(end = 0.5f) { fade(Elements.BlackSquare) } | |
| fractionRange(start = 0.5f) { fade(Elements.RedRect) } | |
| } | |
| }, | |
| ) | |
| } | |
| ... | |
| } | |
| @Composable | |
| fun ContentScope.Foo(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| GreenSquare(...) | |
| BlueCircle(...) | |
| Box( | |
| Modifier.element(Elements.BlackSquare) | |
| .size(80.dp) | |
| .background(Color.Black) | |
| .align(Alignment.BottomEnd) | |
| ) | |
| } | |
| } | |
| @Composable | |
| fun ContentScope.Bar(modifier: Modifier = Modifier) { | |
| Box(modifier.fillMaxSize()) { | |
| GreenSquare(...) | |
| BlueCircle(...) | |
| Box( | |
| Modifier.element(Elements.RedRect) | |
| .size(100.dp, 50.dp) | |
| .background(Color.Red) | |
| .align(Alignment.TopStart) | |
| ) | |
| } | |
| } | |
| ``` | |
| ### Animation spec {#spec} | |
| The transition builder allow you to change the `spec` used to drive the | |
| transition progress during triggered/one-off animations. This `spec` is a normal | |
| Compose | |
| [AnimationSpec\<Float>](https://developer.android.com/reference/kotlin/androidx/compose/animation/core/AnimationSpec) | |
| so you can use normal interpolation curves, springs, keyframes, etc. See | |
| [Customize animations](https://developer.android.com/jetpack/compose/animation/customize) | |
| for more information about the different animation spec available to you. | |
| ```kotlin | |
| transitions { | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| spec = tween(durationMillis = 500) // or spring(...) | |
| ... | |
| } | |
| } | |
| ``` | |
| ### Ranges | |
| By default, transformations start at the beginning of the transition (when | |
| `progress == 0f`) and finish at the end of the transition (when `progress == | |
| 1f`). However, we sometimes need to orchestrate the transformations so that some | |
| of them start later in the transition or finish before the end of the | |
| transition. `SceneTransitionLayout` provides *ranges* so that you can define | |
| when one or more transformations start and/or finish. | |
| Let's see how we can use ranges with our previous example so that the red | |
| rectangle fades out during the first half of the transition and the black square | |
| fades in during the second half, so that we avoid overlapping elements. | |
| {height="200"} | |
| #### fractionRange | |
| You can use `fractionRange {}` to define the `start` and `end` of a | |
| transformation, relative to the overall transition progress. `start` and `end` | |
| must both be in the `[0; 1]` range. | |
| ```kotlin | |
| transitions { | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| spec = spring() | |
| // Fade out the black square during the first half of the transition. | |
| fractionRange(end = 0.5f) { fade(Elements.BlackSquare) } | |
| // Fade in the red rectangle during the second half of the transition. | |
| fractionRange(start = 0.5f) { fade(Elements.RedRect) } | |
| } | |
| } | |
| ``` | |
| #### timestampRange | |
| If the transition [animation spec](#spec) is duration based, you can use | |
| `timestampRange {}` to achieve the same result. | |
| ```kotlin | |
| transitions { | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| spec = tween(durationMillis = 500) | |
| // Fade out the black square during the first half of the transition. | |
| timestampRange(endMillis = 250) { fade(Elements.BlackSquare) } | |
| // Fade in the red rectangle during the second half of the transition. | |
| timestampRange(startMillis = 250) { fade(Elements.RedRect) } | |
| } | |
| } | |
| ``` | |
| ### Transformations | |
| The transformations you can apply to elements are defined in `TransitionBuilder` | |
| and `PropertyTransformationBuilder`. This section illustrates the effect of each | |
| of these transformations. | |
| **Important:** Transformations are **never** applied to **shared** elements, | |
| only to elements that appear or disappear during the transition between scenes. | |
| #### Fade {#fade} | |
| Fades the element in or out by animating the alpha to `0` or `1`. | |
| {height="200"} | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| fade(Elements.BlackSquare) | |
| fade(Elements.RedRect) | |
| } | |
| ``` | |
| #### Translate {#translate} | |
| Translates the element by a fixed amount of dips. | |
| **Tip:** You should also [fade](#fade) elements you are translating to prevent | |
| them from (dis)appearing instantly, unless you are translating from outside the | |
| layout bounds, in which case you should probably use | |
| [edge translate](#edge-translate) instead. | |
| {height="200"} | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| translate(Elements.BlackSquare, x = (-100).dp) | |
| translate(Elements.RedRect, y = 50.dp) | |
| fade(Elements.BlackSquare) | |
| fade(Elements.RedRect) | |
| } | |
| ``` | |
| #### Edge translate | |
| Translates the element from/to an edge of the `SceneTransitionLayout`. | |
| {height="200"} | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| translate(Elements.BlackSquare, Edge.Right) | |
| translate(Elements.RedRect, Edge.Top) | |
| } | |
| ``` | |
| **Tip:** By default the element will start outside of the layout bounds, but you | |
| can set `startsOutsideLayoutBounds` to `false` so that the element starts as | |
| close as possible to the given edge such that the element is fully contained in | |
| the layout. In this case, you should also fade the element so that it doesn't | |
| instantly (dis)appear. | |
| {height="200"} | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| translate(Elements.BlackSquare, Edge.Left, startsOutsideLayoutBounds = false) | |
| translate(Elements.RedRect, Edge.Bottom, startsOutsideLayoutBounds = false) | |
| fade(Elements.BlackSquare) | |
| fade(Elements.RedRect) | |
| } | |
| ``` | |
| #### Anchored translate {#anchored-translate} | |
| Translates an element in the same distance and direction as a **shared** | |
| `anchor` element. | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| anchoredTranslate(Elements.BlackSquare, anchor = Elements.GreenSquare) | |
| fade(Elements.BlackSquare) | |
| } | |
| ``` | |
| {height="200"} | |
| #### Scale drawing {#scale-drawing} | |
| Scale the **visual/drawn** width and/or height of an element. | |
| **Important:** Using `scaleDraw()` does **not** change the size of your element. | |
| If you need the size of the element to have an impact on other elements (like | |
| its siblings or ancestors), use [Scale size](#scale-size) instead. | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| scaleDraw(Elements.BlackSquare, scaleX = 0.5f, scaleY = 0.5f) | |
| scaleDraw(Elements.RedRect, scaleX = 2f, scaleY = 2f) | |
| fade(Elements.RedRect) | |
| fade(Elements.BlackSquare) | |
| } | |
| ``` | |
| {height="200"} | |
| #### Scale size {#scale-size} | |
| Scale the width and/or height of an element. | |
| **Important:** Using `scaleSize()` will change the size of your element and | |
| therefore impact the layout of its parent, children and siblings. If you need to | |
| only scale the drawing result of an element, use [Scale drawing](#scale-drawing) | |
| instead. | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| scaleSize(Elements.BlackSquare, width = 0.5f, height = 0.5f) | |
| scaleSize(Elements.RedRect, width = 2f, height = 2f) | |
| fade(Elements.RedRect) | |
| fade(Elements.BlackSquare) | |
| } | |
| ``` | |
| {height="200"} | |
| #### Anchored size {#anchored-size} | |
| Anchor the size of an element so that it either **starts** with the same size as | |
| a **shared** `anchor` element (when appearing) or **ends** with the same size as | |
| a **shared** `anchor` element (when disappearing). | |
| ```kotlin | |
| from(Scenes.Foo, to = Scenes.Bar) { | |
| anchoredSize(Elements.BlackSquare, anchor = Elements.GreenSquare) | |
| fade(Elements.BlackSquare) | |
| } | |
| ``` | |
| {height="200"} | |
| ### Custom transformations | |
| If the base transformations are not enough for your use case, STL also provides | |
| custom transformations to animate any property (size, offset, alpha or scale) of | |
| any element. These can be added using `TransitionBuilder.transformation()`, to | |
| which you pass the `Transformation.Factory` that is responsible for creating the | |
| `Transformation` for each element matching the `ElementMatcher` passed to that | |
| `transformation()`. | |
| The subclass of `Transformation` that your factory should return depends on | |
| whether the element is shared or not: | |
| * if it is shared, you should return a subclass of | |
| `SharedElementPropertyTransformation`. | |
| * if it is **not** shared, you should return a subclass of | |
| `TransformedElementPropertyTransformation`. | |
| For each of those, there are 2 subclasses available: | |
| * an *"interpolated"* transformation, that returns a *target value* that will | |
| be interpolated automatically for you using the transition progress by STL. | |
| For example, the `fade()` transformation | |
| [is a simple](src/com/android/compose/animation/scene/transformation/Fade.kt) | |
| `InterpolatedPropertyTransformation` that returns `0`. | |
| * a *"custom"* transformation, that returns the value the property should have | |
| for the current frame. For instance, returning `0.3` in a custom alpha | |
| transformation will make the matched elements have a fixed alpha of `0.3` | |
| during the transition. Of course in practice you will usually include the | |
| `transition.progress` in your custom transformation logic to make sure that | |
| the property value is continuous. | |
| Here is a table summarizing which subclass you should return in your | |
| `Transformation.Factory`: | |
| | Shared | Not Shared | |
| -----------: | :----------------------------------------: | :--------: | |
| Interpolated | `InterpolatedSharedPropertyTransformation` | `InterpolatedPropertyTransformation` | |
| Custom | `CustomSharedPropertyTransformation` | `CustomPropertyTransformation` | |
| On top of these, STL will automatically handle interruptions so you can just | |
| focus on the logic for the current transition, and STL will ensure that there is | |
| no instant "jump" (flicker) when a new transition is started while another | |
| transition was already ongoing. | |
| ### Overscroll | |
| In a transition, a progress value typically goes from `0` (means we're on the | |
| first content, scene or overlay) and `1` (means we're on the second content). | |
| Values between 0 and 1 let us animate the transition between the contents. | |
| An **overscroll** happens when the `progress` of the transition goes **below 0** | |
| or **above 1**. | |
| The overscroll effect can be applied to the content to customize how the content | |
| behaves when the scene is overscrolled. | |
| For example, you can use it with the `Modifier.overscroll()` modifier: | |
| ```kotlin | |
| @Composable | |
| fun ContentScope.MyScene() { | |
| Box( | |
| modifier = Modifier | |
| // Apply the vertical effect | |
| .overscroll(verticalOverscrollEffect) | |
| // Apply the horizontal effect | |
| .overscroll(horizontalOverscrollEffect) | |
| ) { | |
| // ... your content ... | |
| } | |
| } | |
| ``` | |
| ### Previews | |
| STL has a built-in preview system for transitions. The preview part of a | |
| transition applies as long as the user is interacting with the transition (i.e. | |
| the user's finger touches the screen). As soon as the finger is lifted from the | |
| screen, the transition switches from the preview part to the regular part. STL | |
| automatically picks up the last animated values from the preview phase and | |
| animates them to their target state during the transition phase. | |
| For example, the below snippet prevents alpha fading during the user gesture. | |
| ```kotlin | |
| from( | |
| SceneA, | |
| to = SceneB, | |
| preview = { exampleTransition(withAlphaFade = false) }, | |
| ) { | |
| exampleTransition(withAlphaFade = true) | |
| } | |
| private fun TransitionBuilder.exampleTransition(withAlphaFade: Boolean) { | |
| if (withAlphaFade) fade(Elements.Content) | |
| // rest of transition definition (scale, translate etc.) | |
| } | |
| ``` | |
| #### Predictive Back | |
| Another prominent use case for a preview is predictive back. Follow the below | |
| steps to add a predictive back preview to your transition. | |
| * You're probably starting with a preexisting transition from one scene back | |
| to another, such as the following example: | |
| ```kotlin | |
| from(Scenes.Bouncer, to = Scenes.Lockscreen) { | |
| bouncerToLockscreenTransition() | |
| } | |
| ``` | |
| * To add a predictive back animation, add a new transition as follows: | |
| ```kotlin | |
| from( | |
| Scenes.Bouncer, | |
| to = Scenes.Lockscreen, | |
| key = TransitionKey.PredictiveBack, | |
| preview = { | |
| fractionRange(easing = Easings.PredictiveBack) { | |
| scaleDraw(Bouncer.Elements.Content, scaleX = 0.8f, scaleY = 0.8f) | |
| translate(Bouncer.Elements.Content, y = 50.dp) | |
| } | |
| }, | |
| ) { | |
| bouncerToLockscreenTransition() // remains unchanged (as above) | |
| } | |
| ``` | |
| Three things to keep in mind: | |
| 1. Make sure to pass the `TransitionKey.PredictiveBack`, which ensures that | |
| this transition is applied during back gestures. | |
| 1. Define the preview animation which will be played during the gesture. | |
| 1. To make the predictive animation feel like all other system-animations, wrap | |
| it with the `fractionRange(easing = Easings.PredictiveBack)` | |
| That’s it! You don’t have to worry about the switch from preview to transition | |
| phase. STL ensures there’s a seamless handover. | |
| ## Interoperability (`AndroidView`) | |
| For `View` interoperability, you can use | |
| [AndroidView](https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose) | |
| in `SceneTransitionLayout` to embed a `View` inside a scene. Your `View` will be | |
| treated as any other element and will be moved and resized when it is shared or | |
| transformed during transitions. | |
| ### (Recommended) Using `Modifier.element()` | |
| The preferred way is to use `Modifier.element()` and have the | |
| `AndroidView.factory` create a new `View` in each scene it is composed. This | |
| means that each scene will have its new copy of the `View`, and that **the | |
| factory will be called whenever we are transitioning to a scene that contains | |
| that element**. | |
| **Tip:** The factory should be lightweight, for instance it should simply | |
| inflate a layout from XML. Make sure to extract any kind of expensive | |
| initialization outside of the factory code. | |
| ```kotlin | |
| @Composable | |
| fun ContentScope.Clock( | |
| clockViewFactory: (Context) -> View, | |
| modifier: Modifier = Modifier, | |
| ) { | |
| AndroidView( | |
| modifier = modifier.element(ClockKey), | |
| factory = clockViewFactory, | |
| update = { TODO() }, | |
| ) | |
| } | |
| ``` | |
| ### Using `MovableElement` | |
| In some cases, your code might assume that your `View` is a singleton and won't | |
| support multiple instances of your View. In that case, the first thing to try is | |
| to refactor your code to eliminate that assumption and use `Modifier.element()`. | |
| If doing this is not feasible, you can use [MovableElement](#movable-elements) | |
| so that your `View` is reused between scenes. | |
| When using `MovableElement`: | |
| 1. The `AndroidView.factory` will be called when transitioning from a scene | |
| that does not contain the element to a scene that contains the element. | |
| 1. The view will be re-attached to a different parent `ViewGroup` when | |
| transitioning to another scene that contains the element. | |
| 1. The view will be detached from its parent when settling to a scene that does | |
| not contain the element. | |
| **Important:** The `AndroidView.factory` can still be called multiple times, so | |
| you are responsible for ensuring that the `View` is a singleton that is memoized | |
| between calls. | |
| **Important:** Using `MovableElement` will bring its own set of complications, | |
| as explained in [Movable elements](#movable-elements). Make sure to carefully | |
| read about them before using it. | |
| ```kotlin | |
| @Composable | |
| fun ContentScope.Clock( | |
| clockViewProvider: (Context) -> View, | |
| modifier: Modifier = Modifier, | |
| ) { | |
| MovableElement(key = ClockKey, modifier) { | |
| content { | |
| AndroidView( | |
| factory = { context -> | |
| val view = clockViewProvider(context) | |
| // The View should not be attached by anything other than | |
| // this AndroidView. | |
| check(view.parent == null) { "View $view is unexpectedly already attached" } | |
| view | |
| }, | |
| update = { TODO() }, | |
| ) | |
| } | |
| } | |
| } | |
| ``` | |
| ## Observing transition state {#observing-transition} | |
| **Important:** Avoid reading/observing the transition state as much as possible. | |
| You should be able to implement most animations using the | |
| [Transition DSL](#transitions) and [animated shared values](#shared-values). | |
| `SceneTransitionLayout` | |
| [hoists](https://developer.android.com/jetpack/compose/state#state-hoisting) the | |
| `SceneTransitionLayoutState` it is using to drive transitions and you can use it | |
| to read/observe the current transition state. | |
| ```kotlin | |
| @Composable | |
| fun SceneTransitionLayoutDemo(modifier: Modifier = Modifier) { | |
| val state = remember { | |
| MutableSceneTransitionLayoutState( | |
| Scenes.Foo, | |
| transitions = transitions { ... }, | |
| ) | |
| } | |
| SceneTransitionLayout( | |
| state = state, | |
| modifier = modifier, | |
| ) { ... } | |
| } | |
| ``` | |
| ### From Compose code | |
| When reading the current transition state from Compose code, you should access | |
| `SceneTransitionLayoutState.transitionState`. It is a `TransitionState` object | |
| whose values are backed by the Compose Snapshot system, so reading them will | |
| automatically cause recomposition/relayout/redrawing depending on where you read | |
| them. | |
| ```kotlin | |
| @Composable | |
| fun TransitionText(state: SceneTransitionLayoutState, modifier: Modifier = Modifier) { | |
| val text = | |
| when (val transitionState = state.transitionState) { | |
| is TransitionState.Idle -> "idle ${transitionState.currentScene}" | |
| is TransitionState.Transition -> | |
| "transition ${transitionState.fromScene} => ${transitionState.toScene}" | |
| } | |
| Text(text, modifier) | |
| } | |
| ``` | |
| ### From anywhere outside Compose code | |
| For interoperability with non Compose code, `SceneTransitionLayout` also | |
| provides `SceneTransitionLayoutState.observableTransitionState()` for a | |
| Flow-based observation of the transition state. | |
| **Important:** Flows usually lead to bad performance and we **strongly** | |
| recommend against using them whenever possible. | |
| ```kotlin | |
| suspend fun logTransitionState(state: SceneTransitionLayoutState) { | |
| state.observableTransitionState().collect { transitionState -> | |
| when (transitionState) { | |
| is ObservableTransitionState.Idle -> { | |
| Log.d(TAG, "idle ${transitionState.currentScene.debugName}") | |
| } | |
| is ObservableTransitionState.Transition -> { | |
| Log.d(TAG, "transition ${transitionState.fromScene} => ${transitionState.toScene}") | |
| } | |
| } | |
| } | |
| } | |
| ``` | |
| ## Nested scrolling | |
| The | |
| [Nested scroll system](https://developer.android.com/develop/ui/compose/touch-input/pointer-input/scroll#nested-scrolling) | |
| allows multiple scrolling components, nested within each other, to work together | |
| by responding to a single scrolling gesture. | |
| In `SceneTransitionLayout`, when a gesture begins on a scrollable component, the | |
| scrollable component will consume the scroll events by default and either | |
| **scroll its content** or perform an **overscroll effect**. | |
| > **Note:** Simple nested scrolling requires no action on your part. Gestures | |
| > that initiate a scrolling action are propagated from children to parents | |
| > automatically, such that when the child can't scroll any further, the gesture | |
| > is handled by its parent element. | |
| > | |
| > from | |
| > ["Automatic nested scrolling" in Android Developer](https://developer.android.com/jetpack/compose/touch-input/pointer-input/scroll#auto-nested-scrolling) | |
| ### Prevents scene transitions from starting mid-scroll when a scrollable has not reached its bounds | |
| Temporarily disable this content swipe actions when any scrollable below this | |
| modifier has consumed any amount of scroll delta, until the scroll gesture is | |
| finished. | |
| This can for instance be used to ensure that a scrollable list is overscrolled | |
| once it reached its bounds instead of directly starting a scene transition from | |
| the same scroll gesture. | |
| ```kotlin | |
| @Composable | |
| fun ContentScope.MyScene() { | |
| Box( | |
| modifier = Modifier | |
| .disableSwipesWhenScrolling() | |
| .verticalScroll(rememberScrollState()) | |
| ) { | |
| // ... your content ... | |
| } | |
| } | |
| ``` | |
| ## Connecting `NestedSceneTransitionLayout`s | |
| With `NestedSceneTransitionLayout` you are able to share elements across | |
| multiple STLs. It enables: | |
| - Transitioning shared elements across nested STLs | |
| - Using DSL to define transitions for elements within a nested STL | |
| > Example: The lockscreen is a STL (Flexiglass). It contains another (nested) | |
| > STL which hold different clock scenes and the various transitions between | |
| > them. The clock is an element of the nested STL but it is also a shared | |
| > element on the shade. Using a nested STL the element can be shared and | |
| > transitioned automatically. Additionally, you might want to use transition DSL | |
| > to target the clock for a transition to the Gone scene (where there is no | |
| > shared clock) and use transition DSL on the outer STL (Flexiglass) to control | |
| > an element within a nested STL (clocks). | |
| #### Known limitations: | |
| - Shared element transitions work only with a descendant/ancestor relationship | |
| but not with NestedSTLs that are side-by-side (siblings). | |
| - None of the NestedSTLs are allowed to share the same `ElementKey`, not even | |
| siblings | |
| - Interruptions are not fully supported for complex scenarios where a shared | |
| element appears in more than 2 scenes simultaneously (Can happen when the | |
| parent and child STL transition at the same time). Transitions will work but | |
| may jump cut under certain conditions. | |
| #### Usage example | |
| The `NestedSceneTransitionLayout` Composable is defined on the `ContentScope` of | |
| any `SceneTransitionLayout` or `NestedSceneTransitionLayout`. It can be used the | |
| same like a normal STL. | |
| ```kotlin | |
| SceneTransitionLayout( | |
| state = state, | |
| ) { | |
| scene(ParentSTL.Scenes.Left) { | |
| // Outer STL Left Content (is a nested STL) | |
| NestedSceneTransitionLayout( | |
| state = childState, | |
| modifier = Modifier.fillMaxSize(), | |
| ) { | |
| scene(ChildSTL.Scenes.Top) { | |
| Box(Modifier.fillMaxSize()) { | |
| // Nested STL Top Content | |
| } | |
| } | |
| scene(ChildSTL.Scenes.Bottom) { | |
| Box(Modifier.fillMaxSize()) { | |
| // Nested STL Bottom Content | |
| } | |
| } | |
| } | |
| } | |
| scene(ParentSTL.Scenes.Right) { | |
| Box(Modifier.fillMaxSize()) { | |
| // Outer STL Right Content | |
| } | |
| } | |
| } | |
| ``` | |
| The `ParentSTL` can then reference elements from within the `ChildSTL` as if its | |
| their own. | |
| ## SceneTransitionLayoutDebugger | |
| The SceneTransitionLayoutDebugger app can help you easily get visual insights | |
| into the STL, transitions, content and element hierarchy and lets you quickly | |
| understand where elements are being composed. It also adds detailed logging to | |
| track element state and the inner `Element.kt` loop. | |
| | |
| <div style="display: flex; justify-content: center; gap: 5px;"> | |
| <img src="docs/debugger_config.png" style="width: 40%; display: inline-block;" /> | |
| <img src="docs/debugger_result.png" style="width: 40%; display: inline-block;" /> | |
| </div> | |
| | |
| ```shell | |
| m SceneTransitionLayoutDebugger | |
| APK_PATH=$(find $ANDROID_PRODUCT_OUT -name SceneTransitionLayoutDebugger.apk) | |
| echo "Installing APK from: $APK_PATH" | |
| adb install "$APK_PATH" | |
| ``` | |
| You can also set debug values through adb. This is useful e.g. when you are | |
| currently seeing a transient bug state and can't switch to the app. See | |
| instructions | |
| [here](src/com/android/compose/animation/scene/debug/StlDebugConfig.kt). For | |
| other cases the app should be more convenient to use and also provides | |
| documentation for all functions and a preview section. |