Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Standard Android animation can be utilized to switch screens in a single activity Compose application by implementing the following steps:

  1. Add a Navigation component to the project by adding the following dependencies to the app's build.gradle file:
def nav_version = "2.3.5"

implementation "androidx.navigation:navigation-compose:$nav_version"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
  1. Create a NavHost Composable by adding the following code to the main Composable function:
val navController = rememberNavController()
NavHost(navController, startDestination = "home") {
   composable("home") { HomeScreen(navController) }
   composable("settings") { SettingsScreen(navController) }
}
  1. Create the screens for the app by adding the following Composable functions:
@Composable
fun HomeScreen(navController: NavController) {
   // Content for the home screen
}

@Composable
fun SettingsScreen(navController: NavController) {
   // Content for the settings screen
}
  1. Add a button or other user interface element to the HomeScreen Composable that will navigate to the SettingsScreen:
Button(onClick = { navController.navigate("settings") }) {
   Text(text = "Go to settings")
}
  1. Finally, add a transition animation to the screen transition by adding the following code to the HomeScreen Composable:
val transition = updateTransition(targetState = true, label = "Button Transition")
val buttonOffset by transition.animateDp(
   label = "Button Offset",
   transitionSpec = {
      slideInHorizontally({ width -> width }) + fadeIn() with
      slideOutHorizontally({ width -> -width }) + fadeOut()
   }
) { if (it) 16.dp else 0.dp }

Button(
   onClick = { navController.navigate("settings") },
   modifier = Modifier.offset(buttonOffset)
) {
   Text(text = "Go to settings")
}

This code will animate the button as it transitions to the SettingsScreen.