Menu Flashcards
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?
- Add a menu xml with an ^item^ element for each option.
- Wrap the Activity’s root view in a ^androidx.drawerlayout.widget.DrawerLayout^ tag, wrapped in turn by a ^layout^ tag
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" /^
- Add the following to Activity.onCreate( ) or Fragment.onCreateView( ) :
NavigationUI.setupWithNavController(binding.navViewXmlId, navController, drawerLayout)
// third parameter, drawerLayout (from binding) is optional - it adds navigation drawer from app bar’s drawer button.
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