How to add an options menu to the Fragment?
Call setHasOptionsMenu(true) in Fragment.onCreateView
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.my_menu_xml, menu)
}
How to handle menu item clicks?
CUSTOM HANDLING
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle using item.itemId (matches menu xml ^item^ ids)
return true
}WHEN MENU ITEM IDs MATCH FRAGMENT IDs IN NAV_GRAPH
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return NavigationUI.onNavDestinationSelected(item, requireView( ).findNavController( )) || super.onOptionsItemSelected(item)
}
Which dependency is required to implement a navigation drawer?
implementation “com.google.android.material:material:$version”
(The nav drawer is part of the Material Components for Android library (material.io))
How to add a navigation drawer to a layout xml?
3. Add the following just before the closing ^/layout^ tag: ^com.google.android.material.navigation.NavigationView android:id="@+id/navView" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/nav_header" app:menu="@menu/navdrawer_menu" /^
5. override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.myNavHostFragment)
return NavigationUI.navigateUp(navController, drawerLayout)
}
// NB This implementation is slightly different if there is an options menu without a nav drawer (see Activities & Fragments, card 10)As with the options menu, if the item id’s match the fragment id’s in the nav_graph then no need to implement clickListeners