Skip to content

Instantly share code, notes, and snippets.

@skydoves
Last active April 19, 2024 06:45
Show Gist options
  • Save skydoves/b9da99c7081bab1296a7c326ff797cf0 to your computer and use it in GitHub Desktop.
Save skydoves/b9da99c7081bab1296a7c326ff797cf0 to your computer and use it in GitHub Desktop.
shared_element_navigation
@Composable
fun NavigationComposeShared() {
SharedTransitionLayout {
val pokemons = remember {
listOf(
Pokemon("Pokemon1", R.drawable.pokemon_preview),
Pokemon("Pokemon2", R.drawable.pokemon_preview),
Pokemon("Pokemon3", R.drawable.pokemon_preview),
Pokemon("Pokemon4", R.drawable.pokemon_preview)
)
}
val boundsTransform = { _: Rect, _: Rect -> tween<Rect>(1400) }
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "home") {
composable("home") {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
itemsIndexed(pokemons) { index, item ->
Row(
modifier = Modifier.clickable {
navController.navigate("details/$index")
}
) {
Image(
painter = painterResource(id = item.image),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.sharedElement(
rememberSharedContentState(key = "image-$index"),
animatedVisibilityScope = this@composable,
boundsTransform = boundsTransform
)
.padding(horizontal = 20.dp)
.size(100.dp)
)
Text(
text = item.name,
fontSize = 18.sp,
modifier = Modifier
.sharedElement(
rememberSharedContentState(key = "text-$index"),
animatedVisibilityScope = this@composable,
boundsTransform = boundsTransform
)
.align(Alignment.CenterVertically)
)
}
}
}
}
composable(
"details/{pokemon}",
arguments = listOf(navArgument("pokemon") { type = NavType.IntType })
) { backStackEntry ->
val pokemonId = backStackEntry.arguments?.getInt("pokemon")
val pokemon = pokemons[pokemonId!!]
Column(
Modifier
.fillMaxSize()
.clickable {
navController.navigate("home")
}) {
Image(
painterResource(id = pokemon.image),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.aspectRatio(1f)
.fillMaxWidth()
.sharedElement(
rememberSharedContentState(key = "image-$pokemonId"),
animatedVisibilityScope = this@composable,
boundsTransform = boundsTransform
)
)
Text(
pokemon.name, fontSize = 18.sp, modifier =
Modifier
.fillMaxWidth()
.sharedElement(
rememberSharedContentState(key = "text-$pokemonId"),
animatedVisibilityScope = this@composable,
boundsTransform = boundsTransform
)
)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment