How to animate navigation in Android Wear OS Compose

335 views Asked by At

What I want is some screen transition code with a sliding animation.

val navController = rememberSwipeDismissableNavController()

SwipeDismissableNavHost(
                navController = swipeDismissableNavController,
                startDestination = Screen.FirstScreen.route,
                modifier = modifier
            ) {

composable(route = Screen.FirstScreen.route) {
   navController.navigate(Screen.SecondScreen.route)
}

composable(route = Screen.SecondScreen.route)
.
.

}

How do I handle animation here?

val option = NavOptions.Builder()
                            .setEnterAnim(R.anim.slide_in_left)
                            .setExitAnim(R.anim.slide_out_right)
                            .build()
                        
navController.navigate(Screen.RecordNotUploadScreen.route, option)

This code doesn't work

1

There are 1 answers

2
alonah edmund On

Here is the code to achieve screen transitions with sliding animations in Android Wear OS Compose:

val navController = rememberSwipeDismissableNavController()

SwipeDismissableNavHost(
    navController = navController,
    startDestination = Screen.FirstScreen.route,
    modifier = modifier
) {
    composable(route = Screen.FirstScreen.route) {
        // Your content for the first screen
        Button(onClick = {
            navController.navigate(Screen.SecondScreen.route)
        }) {
            Text("Go to Second Screen")
        }
    }

    composable(route = Screen.SecondScreen.route) {
        // Your content for the second screen
        // ...
    }
}

To handle animations, you can use the rememberAnimatedNavController provided by Compose Navigation. Make sure you have the appropriate navigation dependencies added to your project. Here's an example:

val navController = rememberAnimatedNavController()

SwipeDismissableNavHost(
    navController = navController,
    startDestination = Screen.FirstScreen.route,
    modifier = modifier
) {
    // Composables for each screen
}

// Define your animation resources (slide_in_left.xml and slide_out_right.xml) in the res/anim directory

// Then use NavOptions to specify animations when navigating
val option = NavOptions.Builder()
    .setEnterAnim(R.anim.slide_in_left)
    .setExitAnim(R.anim.slide_out_right)
    .build()

navController.navigate(Screen.SecondScreen.route, options = option)

Ensure that you have the slide_in_left.xml and slide_out_right.xml animation files defined in the res/anim directory of your Android Wear OS project. These files should contain appropriate animation definitions for your sliding animation effect.