It is very easy to implement screen navigation in jetpack compose. whenever a
user goes to another screen from the current screen then the user can go back
to the previous screen by pressing the back button. I'll show you how you
could implement the same without having two activities. For this, I would like
to create two Composables functions describing the home screen and text
screen. the home screen can launch a text screen and you go back to it
whenever you press the back button.
Let's start by creating a sealed class for all of the screens that your app
might have, as well as a state for the current screen.
sealed class Screen (val name : String) { object HomeScreen : Screen("Home Screen") object TextScreen : Screen("Text Screen") } object Navigation { val currentScreen : MutableState<Screen> = mutableStateOf(Screen.HomeScreen) fun navigateTo(screen: Screen) { currentScreen.value = screen } }
The Navigation object maintains the current screen state. Look at the state
diagram given below.
Home screen
@Composable fun HomeScreen() { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { ScreenLaunchButton(screen = Screen.TextScreen) } } @Composable fun ScreenLaunchButton(screen: Screen) { Button( onClick = { // draw another screen Navigation.navigateTo(screen) } ) { Text(screen.name) } }
the home screen has a button, on pressing it, it changes the current screen
state with the text screen.
Text screen
@Composable fun ScreenText() { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { MyText() } OnBackButtonPress { // not implemented Navigation.navigateTo(Screen.homeScreen) } } // I've write another post for Implementation of OnBackButtonPress() // read "Back button press handler in jetpack compose". @Composable fun MyText() { Text( text = "Jetpack compose", ) }
Draw the current screen
@Composable fun Content() { // this recomposes whenever currentScreen state changes Crossfade(targetState = Navigation.currentScreen) { screen -> when(screen.value) { Screen.homeScreen -> HomeScreen() Screen.TextScreen -> ScreenText() } } }