- Add a
NavHost
to your app's layout. TheNavHost
will act as a container for your app's screens, and it will handle the navigation between them.
2. Define the screens that you want to navigate between as composables. Each screen should be a composable function that returns a @Composable
element.
3. Create a Navigator
object that defines the navigation between the screens. The Navigator
object should specify the composables that represent the screens, as well as the actions that should be taken when navigating between them.
4. Use the findNavController
function to get a reference to the NavController
for the NavHost
.
5. Call the navigate
function on the NavController
to navigate to a different screen.
Here’s an example of how you can use these steps to navigate from one screen to another:
// Define the screens as composables
@Composable
fun HomeScreen() {
// Home screen content goes here
Button(onClick = {
// Navigate to the profile screen when the button is clicked
findNavController().navigate(R.id.profile_screen)
})
}
@Composable
fun ProfileScreen() {
// Profile screen content goes here
}
// Create a Navigator object that defines the navigation between the screens
val navigator = Navigator {
composable("home_screen") {
HomeScreen()
}
composable("profile_screen") {
ProfileScreen()
}
}
// Add a NavHost to the app's layout
NavHost(navigator = navigator) {
// NavHost content goes here
}
In this example, we’ve defined two screens: HomeScreen
and ProfileScreen
. We've also created a Navigator
object that defines the navigation between these screens.
When the user clicks the button in the HomeScreen
, the navigate
function is called on the NavController
, and the app navigates to the ProfileScreen
.
Happy Coding!