// Step 1: Add dependencies to your app/build.gradle file
implementation "androidx.navigation:navigation-fragment-ktx:2.3.5"
implementation "androidx.navigation:navigation-ui-ktx:2.3.5"
// Step 2: Create a navigation graph resource file (res/navigation/nav_graph.xml)
// Define your destinations and actions in this file
// Step 3: Set up your activity_main.xml layout with a DrawerLayout and a NavigationView
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"/>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
// Step 4: Create a menu resource file (res/menu/nav_menu.xml)
// Define your menu items with corresponding ids
// Step 5: Initialize NavController in your MainActivity
val navController = findNavController(R.id.nav_host_fragment)
// Step 6: Set up the AppBarConfiguration with the top-level destinations
val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment, R.id.profileFragment), drawerLayout)
// Step 7: Set up the ActionBar with NavController and AppBarConfiguration
setupActionBarWithNavController(navController, appBarConfiguration)
// Step 8: Set up NavigationView with NavController
navView.setupWithNavController(navController)
// Step 9: Handle navigation item clicks in your MainActivity
navView.setNavigationItemSelectedListener { menuItem ->
menuItem.isChecked = true
drawerLayout.closeDrawers()
when (menuItem.itemId) {
R.id.nav_home -> {
// Navigate to HomeFragment
navController.navigate(R.id.homeFragment)
true
}
R.id.nav_profile -> {
// Navigate to ProfileFragment
navController.navigate(R.id.profileFragment)
true
}
// Add more cases for other menu items if needed
else -> false
}
}