Android Navigation Component — Complete Guide
In this tutorial, you'll learn about Android Navigation Component. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your NavController crashes with navigation destination unknown, or the back button doesn't work as expected after navigating.
Wrong Approach ❌
// Setting NavController manually — simple but fragile
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navController = findNavController(R.id.nav_host_fragment)
navController.navigate(R.id.action_to_home) // May crash if nav graph not set
}
}
// Using AppBarConfiguration without proper setup
val navController = findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController) // Works but...
// Missing onSupportNavigateUp override
Output: IllegalArgumentException: navigation destination unknown. Back button doesn't work.
Right Approach ✅
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
// Set up action bar with navigation
val appBarConfiguration = AppBarConfiguration(
setOf(R.id.homeFragment, R.id.dashboardFragment) // Top-level destinations
)
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
// Safe navigation using NavDirections
fun safeNavigate() {
try {
findNavController().navigate(
HomeFragmentDirections.actionHomeToDetails(itemId = 42)
)
} catch (e: IllegalArgumentException) {
// Handle navigation error gracefully
}
}
Output: Proper navigation with working back button and action bar integration.
Prevention
- Always use
NavDirections(generated by Safe Args) for navigation. - Override
onSupportNavigateUp()and delegate tonavController.navigateUp(). - Define
AppBarConfigurationwith top-level destinations. - Handle navigation errors with try/catch.
Common Mistakes with navigation component
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- 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
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