This story is for those who are still not aware of the Navigation Component. Here we will go over the main elements of the library and see how it all looks.
You are now in the first part of a large article about Navigation Component in a multi-module project. If you are already familiar with the basics, then I recommend going further to the parts:
How Safe Args plugin works and what it does .
Working with the Navigation Component in a multi-module project in conjunction with SafeArgs .
Solution for iOS-like multistack navigation
TL; DR .:
To organize navigation in the application using the Navigation Component, you need:
Create a graph;
Add screens to it;
Add transitions between them;
Add nested graphs if needed;
Putting all this mess in NavHost;
Indicate transitions in code.
Basic navigation components
1. The Navigation Graph is the fundamental unit of navigation. It is a graph in which vertices are screens and edges are transitions between them. The graph is created in a separate xml file in the res / navigation folder. In order not to mislead the navController, you need to specify its start point (startDestination) in the graph.
2. Destination represents the UI unit on the graph (Fragment / Activity / Dialog / NestedGraph).
3. Action destination- . ( ), ( , ).
4. Nested Graph — . , <include>.
5. NavHost — , . , NavHostFragment, . :
<androidx.fragment.app.FragmentContainerView
android:id="@+id/navHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_main" />
6. NavController — , . . NavController — , , , , , shared- .
Transitions between screens
Transitions between screens can be done through Action or through DeepLink.
Transition with Action
What it looks like:
<action
android:id=”@+id/action_to_user_details”
app:destination=”@id/userDetailsFragment”
app:enterAnim=”@anim/add_fragment_animation”
app:exitAnim=”@anim/pop_fragment_animation”
app:popEnterAnim=”@anim/pop_enter_animation”
app:popExitAnim=”@anim/pop_exit_animation”>
Calling the transition:
navController.navigate( R.id.action_to_user_details, Bundle().apply {putString(USER_ID, userId)} )
Getting arguments on the "other end":
private val userID by lazy {
arguments!![USER_ID]
}
Navigating with deep link
What it looks like:
<deepLink
app:uri=”app://customUri?parameter={parameterName}”
/>
Calling the transition:
navController.navigate(
Uri.parse(“app://customUri?parameter=$reason”)
)
Getting arguments on the "other end":
private val refundId by lazy {
arguments?.getString(“parameter”, null)
}
That's all! Simple and straightforward - this is what the Navigation Component captivates with. Now let's dive into how the Safe Args plugin works and what it does and get down to working with the Navigation Component in a multi-module project together with SafeArgs and iOS-like multistack navigation .