Transition with Shared Element
At this point, you’re just one step away from the transition.
Open ListScreen.kt, find Image
in the ListItem
Composable. Wrap Image
with sharedTransitionScope
as follows:
with(sharedTransitionScope) {
Image(
painter = painterResource(id = item.imageId),
contentDescription = stringResource(id = item.imageId),
modifier = Modifier
.size(size = 80.dp)
.sharedElement(
state = rememberSharedContentState(key = item.imageId),
animatedVisibilityScope = animatedVisibilityScope,
)
)
}
Pay attention to the parameters in the sharedElement()
modifier here:
- The
state
parameter tags a layout with a key such that entering and exiting shared elements are of the same key, sharing the same animation effect.
- The
animatedVisibilityScope
parameter ensures only the elements being rendered for the transition, which is within the scope.
Note: Be careful when working with lists. You need to use a different unique identifier for every item participating in the animation.
Do the same for the Image
in the DetailScreen
Composable since that’s your destination layout:
with(sharedTransitionScope) {
Image(
painter = painterResource(id = item.imageId),
contentDescription = stringResource(id = item.imageId),
contentScale = ContentScale.Fit,
modifier =
Modifier.fillMaxWidth()
.height(300.dp)
.background(color = Color.White)
.sharedElement(
rememberSharedContentState(key = item.imageId),
animatedVisibilityScope = animatedVisibilityScope
)
)
}
Note that item.imageId
is used as a key among your shared elements. This will be unique for each item in the list.
Build and run one last time, and tap any list item to see the magic!
Congratulations, you’ve mastered the art of transitions and turned a simple app into an awesome one!!
Where To Go From Here?
Get the final project by clicking the Download Materials button at the top or bottom of this tutorial.
Keep your users enchanted with the magic of Android animations. Here are some additional resources to explore:
- No interoperability between Views and Compose
- No built-in support for automatic animation between shapes – for example, animating from a square to a circle.
Current Limitations of Transition APIs in Compose:
- No interoperability between Views and Compose
- No built-in support for automatic animation between shapes – for example, animating from a square to a circle.
I hope learning the transition animations helps you create amazing user experiences for your next Compose app. If you have questions or comments, please join the forum discussion and comment below!