Goodbye navigation nightmares!
Continuing in the theme of new ways of doing common things required of an Android dev I wanted to show some basic usage of the Jetpack Navigation libraries to develop a hypothetical onboarding flow that will also use a shared view model to share information between fragments and SafeArgs to provide basic information to destinations with type safety.
Let’s start by creating a new project with an empty activity:
Give it a name and min SDK. I left all options at their default, including using Kotlin and named my project ‘Nav Sample’.
The first thing we should do is add the relevant dependencies to our app level build.gradle file. There are multiple dependencies that include support for feature modules, testing and Jetpack Compose but for our purposes we will simply use the following:
The Navigation Graph
The navigation graph is effectively a map (xml file) of destinations (activities, fragments, dialogs) with interconnections described by actions and arguments. This map allows simple navigation between destinations without having to manually create intents.
The map can be edited via the xml directly, or more conveniently, by using the Android Studio design view to create new destinations and connections by dragging and dropping.
To create a new nav graph we need to first create a new Android resource file to store the information.
- Right-click app -> res
- Click New -> Android Resource File
Call this file nav_graph and choose resource type: Navigation. Click ‘OK’.
You should now see your empty navigation graph in the design view:
Adding the Fragment container
We now need to create a container to hold our fragments (destinations).
Open activity_main.xml (generated for your blank activity) and replace the contents with the following:
So instead of the default TextView we have a FragmentContainerView and the two main things to note here are:
This is important as it registers this container as the nav host that will intercept the system back button. You can have multiple nav hosts but only one default; for our purposes we only want a single nav host and it will be the default.
This is what creates the association between our FragmentContainerView and the navigation graph we created above.
Adding a Start Destination
Open up the nav_graph.xml in the ‘Design’ view and click the ‘+’ icon to add a destination and click ‘create new destination’:
On the next screen, choose ‘Fragment (blank)’ and name this fragment ‘WelcomeFragment’.
You should now see your fragment as a destination on your nav graph, and as it’s the first (only) destination we’ve created it is automatically set as the start destination, indicated by the little house icon above like below:
This can be changed in the future by right clicking any destination and choosing “Set as Start Destination”.
Running The App
Building and running the app should now load up the Welcome Fragment.
In part 2 we’ll make some more destinations and navigate between them.