Jetpack Compose Flat and Hierarchical Navigation
- Navigation in your app has to be appropriate: Don’t use non-logical navigation.
- Navigation must always be intuitive: Users don’t have time to look for the right section in your app
- Don’t steal time from your users: They will delete the app
- Navigation must be clear: Users have to always know which screen they are on now
When building a business application the 2 main navigation structures are Hierarchical and Flat.
Hierarchical
Users navigate by making only one choice per screen until they reach their destination. To get to another destination, users must either retrace, or start from the beginning and make other choices.
We use NavHostController to implement hierarchical navigation
Add this to your project by updating your app module’s build.gradle dependencies
dependencies {
...
implementation("androidx.navigation:navigation-compose:2.4.0-alpha10")
}
Then create a Router component to do all route management. Within this router we map 2 screens to 2 routes: “screen1" and “child1". We keep track of all nav state through a hoisted navController state which is passed down to all routed components.
Clicking on the Button on Screen 1 will push the child screen onto Screen 1
Flat
Now let’s look at Flat navigation. All the primary screens can be navigated from the main screen. We’ll build and use a BottomNavigation Bar to implement flat navigation.
First Let’s add another screen (screen2) to the Router
Now let’s create a BottomNavigationBar, a component that takes in a list of nav items, a nav controller, and an item click handler. It then loops through nav items to display them in within a BottomNavigation. Note the BottomNavigation returns a RowScope so all items rendered in this component will automatically be rendered in a row.
The last step is to change the MainActivity to return a Scaffold with a bottomBar.
Final result: