DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Shared Element Transitions in Jetpack Compose

Shared Element Transitions create beautiful, fluid animations when navigating between screens by animating shared elements from one screen to another.

Understanding SharedTransitionLayout

The SharedTransitionLayout composable enables shared element animations:

@Composable
fun NavigationWithTransitions() {
    val showDetail = remember { mutableStateOf(false) }

    SharedTransitionLayout {
        if (!showDetail.value) {
            ListScreen(
                onItemClick = { showDetail.value = true },
                sharedTransitionScope = this
            )
        } else {
            DetailScreen(
                onBack = { showDetail.value = false },
                sharedTransitionScope = this
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Shared Element Animation Implementation

@Composable
fun ListItem(
    item: Item,
    sharedTransitionScope: SharedTransitionScope,
    onClick: () -> Unit
) {
    with(sharedTransitionScope) {
        Box(
            modifier = Modifier
                .sharedElement(
                    state = rememberSharedContentState(key = "item_${item.id}"),
                    animatedVisibilityScope = this@AnimatedVisibilityScope
                )
                .clickable(onClick = onClick)
        ) {
            Image(
                painter = painterResource(item.imageRes),
                contentDescription = null
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Animating Multiple Elements

Share multiple elements simultaneously:

@Composable
fun DetailScreen(
    item: Item,
    sharedTransitionScope: SharedTransitionScope
) {
    with(sharedTransitionScope) {
        Column {
            Image(
                modifier = Modifier.sharedElement(
                    state = rememberSharedContentState(key = "item_${item.id}"),
                    animatedVisibilityScope = this@AnimatedVisibilityScope
                )
            )
            Text(
                text = item.title,
                modifier = Modifier.sharedElement(
                    state = rememberSharedContentState(key = "title_${item.id}"),
                    animatedVisibilityScope = this@AnimatedVisibilityScope
                )
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Shared element transitions provide a polished, professional feel to your app's navigation.


8 Android app templates available on Gumroad

Top comments (0)