How to use Navigation Drawer and Bottom Navigation simultaneously - Navigation Architecture Component
No need of writing separate code to replace the back button with the drawer icon.
In AppBarConfiguration pass the fragment ids (from nav_graph) which you are using to navigate from both bottom navigation & navigation drawer. (P.S fragments and its associated icon should have same ids)
For your case the AppBarConfiguration should look like this :
appBarConfig = AppBarConfiguration.Builder(R.id.starFragment, R.id.statsFragment, R.id.userFragment)
.setDrawerLayout(drawerLayout)
.build()
Setup the action bar :
setSupportActionBar(toolbar)
setupActionBarWithNavController(navController, appBarConfig)
Now setup navcontroller for both bottom navigation & navigation view :
navView.setupWithNavController(navController)
bottomNav.setupWithNavController(navController)
onSupportNavigateUp function should should be :
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfig)
}
Back button press should be handled if drawer is open :
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
Bonus
By default when you click bottom navigation icon in the order icon_1 then icon_2 then icon_3 and from there you press back button it will navigate back to home icon that's icon_1
If you want to navigate back in the reverse order in which you have clicked the icons (back stack manner) then add android:menuCategory="secondary" to the item in the menu. So your menu will be like :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/starFragment"
android:icon="@drawable/ic_star_green_48dp"
android:title="@string/bottom_nav_title_star"
android:menuCategory="secondary"/>
<item
android:id="@+id/statsFragment"
android:icon="@drawable/ic_stats_green_48dp"
android:title="@string/bottom_nav_title_stats"
android:menuCategory="secondary"/>
<item
android:id="@+id/userFragment"
android:icon="@drawable/ic_user_green_48dp"
android:title="@string/bottom_nav_title_user"
android:menuCategory="secondary"/>
</menu>
Hope the back button icon will be solved now :)
This project uses DrawerLayout and simulates BottomNavigationView using RadioButtons, this is the way I found to solve the problem
In the Google Codelab navigation project they do what Adithya T Raj mention but it only serves to show the DrawerLayout on landscape and BottomNavigationView on Portrait. The project link:
I try to force them to show me both on this branch but only the DrawerLayout is shown