Android Navigation Graph — Complete Guide
In this tutorial, you'll learn about Android Navigation Graph. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your navigation graph has too many fragments in one file, nested graphs don't work, or deep links navigate to the wrong destination.
Wrong Approach ❌
<!-- One giant nav graph with all destinations -->
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
app:startDestination="@id/homeFragment">
<fragment android:id="@+id/homeFragment" ... />
<fragment android:id="@+id/profileFragment" ... />
<fragment android:id="@+id/settingsFragment" ... />
<fragment android:id="@+id/aboutFragment" ... />
<fragment android:id="@+id/helpFragment" ... />
<!-- 50+ destinations in ONE file -->
</navigation>
Output: Massive XML file, slow build times, hard to maintain.
Right Approach ✅
<!-- Main nav graph with nested graphs -->
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
app:startDestination="@id/home_graph">
<!-- Feature-specific nested graph -->
<navigation android:id="@+id/home_graph"
app:startDestination="@id/homeFragment">
<fragment android:id="@+id/homeFragment" ... />
<fragment android:id="@+id/detailsFragment" ... />
<deepLink app:uri="myapp://details/{id}" />
</navigation>
<navigation android:id="@+id/profile_graph"
app:startDestination="@id/profileFragment">
<fragment android:id="@+id/profileFragment" ... />
<fragment android:id="@+id/editProfileFragment" ... />
</navigation>
<!-- Include external nav graphs -->
<include app:graph="@navigation/settings_graph" />
</navigation>
Output: Modular, maintainable navigation structure.
Prevention
- Split nav graph by feature (one graph per feature).
- Use nested
<navigation>elements for feature modules. - Use
<include>to import nav graphs from other modules. - Define deep links within the specific destination or sub-graph.
Common Mistakes with navigation graph
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro