Nested navigation graphs help organize app screens into smaller groups. This makes your app easier to manage and navigate.
Nested navigation graphs in Android Kotlin
val navController = findNavController(R.id.nav_host_fragment) val nestedGraph = navController.navInflater.inflate(R.navigation.nested_graph) navController.graph.addDestination(nestedGraph)
You define nested graphs in separate XML files inside the res/navigation folder.
Use <include> tag in your main navigation XML to include nested graphs.
settings_graph.<?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_graph" app:startDestination="home_fragment"> <fragment android:id="@+id/home_fragment" android:name="com.example.HomeFragment" android:label="Home" /> <include app:graph="@navigation/settings_graph" /> </navigation>
<?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/settings_graph" app:startDestination="settings_fragment"> <fragment android:id="@+id/settings_fragment" android:name="com.example.SettingsFragment" android:label="Settings" /> <fragment android:id="@+id/profile_fragment" android:name="com.example.ProfileFragment" android:label="Profile" /> </navigation>
This is a simple activity that hosts the navigation component. The navigation XML files define the nested graphs.
import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController // The main graph includes the nested settings graph via XML // Navigation works seamlessly between home and settings/profile screens } }
Nested graphs help keep navigation organized and modular.
Time complexity: Navigation actions are fast and constant time.
Common mistake: Forgetting to set the start destination in nested graphs causes navigation errors.
Use nested graphs when you want to separate flows logically, instead of putting all screens in one big graph.
Nested navigation graphs group related screens for better organization.
Use <include> in XML to add nested graphs inside main graph.
This makes your app easier to maintain and navigate.